Javascript atob(str) equivilent in c#

    var str = "eyJpc3MiOiJodHRwczovL2lkZW50aXR5LXN0YWdpbmcuYXNjZW5kLnh5eiIsImF1ZCI6Imh0dHBzOi8vaWRlbnRpdHktc3RhZ2luZy5hc2NlbmQueHl6L3Jlc291cmNlcyIsImNsaWVudF9pZCI6IjY5OTRBNEE4LTBFNjUtNEZFRC1BODJCLUM2ODRBMEREMTc1OCIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJzdWIucmVhZCIsImRhdGEud3JpdGUiLCJkYXRhLnJlYWQiLCJhbGcuZXhlY3V0ZSJdLCJzdWIiOiIzNzdjMDk1Yi03ODNiLTQ3ZTctOTdiMS01YWVkOThjMDM4ZmMiLCJhbXIiOiJleHRlcm5hbCIsImF1dGhfdGltZSI6MTQwNzYxNTUwNywiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvMDg0MGM3NjAtNmY3Yi00NTU2LWIzMzctOGMwOTBlMmQ0NThkLyIsIm5hbWUiOiJwa3NAYXNjZW5kLnh5eiIsImV4cCI6MTQwNzgzNjcxMSwibmJmIjoxNDA3ODMzMTExfQ";
    int mod4 = str.Length % 4;
    if (mod4 > 0)
    {
        str += new string('=', 4 - mod4);
    }

solved it in c#


Use javascript's window.btoa function to encode the string in Base 64 Format in Javascript Frontend UI. To decode back same string in C# (the equivalent of javascript's window.atob function) please see the following code.

(Most probably you are trying to post back data (HTML in most cases as it requires btoa encoding to ensure the best compatibility)) back to the controller or you might creating custom basic basic authentication filter on server side)

string base64Encoded = "YmFzZTY0IGVuY29kZWQgc3RyaW5n";
string base64Decoded;
byte[] data = System.Convert.FromBase64String(base64Encoded);
base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data);
Console.WriteLine(base64Decoded)

You can see its working sample at https://dotnetfiddle.net/abxwSw

Tags:

Javascript

C#