我这样做了:
byte[] data = Convert.FromBase64String(str);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
但获得了Unhandled Exception: System.FormatException: Invalid length for a Base-64 char array or string.
在javascript中使用atob(str)
给我正确的解码str。
javascript console:
atob("eyJpc3MiOiJodHRwczovL2lkZW50aXR5LXN0YWdpbmcuYXNjZW5kLnh5eiIsImF1ZCI6Imh0dHBzOi8vaWRlbnRpdHktc3RhZ2luZy5hc2NlbmQueHl6L3Jlc291cmNlcyIsImNsaWVudF9pZCI6IjY5OTRBNEE4LTBFNjUtNEZFRC1BODJCLUM2ODRBMEREMTc1OCIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJzdWIucmVhZCIsImRhdGEud3JpdGUiLCJkYXRhLnJlYWQiLCJhbGcuZXhlY3V0ZSJdLCJzdWIiOiIzNzdjMDk1Yi03ODNiLTQ3ZTctOTdiMS01YWVkOThjMDM4ZmMiLCJhbXIiOiJleHRlcm5hbCIsImF1dGhfdGltZSI6MTQwNzYxNTUwNywiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvMDg0MGM3NjAtNmY3Yi00NTU2LWIzMzctOGMwOTBlMmQ0NThkLyIsIm5hbWUiOiJwa3NAYXNjZW5kLnh5eiIsImV4cCI6MTQwNzgzNjcxMSwibmJmIjoxNDA3ODMzMTExfQ")
"{"iss":"https://identity-staging.ascend.xyz","aud":"https://identity-staging.ascend.xyz/resources","client_id":"6994A4A8-0E65-4FED-A82B-C684A0DD1758","scope":["openid","profile","sub.read","data.write","data.read","alg.execute"],"sub":"377c095b-783b-47e7-97b1-5aed98c038fc","amr":"external","auth_time":1407615507,"idp":"https://sts.windows.net/0840c760-6f7b-4556-b337-8c090e2d458d/","name":"pks@ascend.xyz","exp":1407836711,"nbf":1407833111}"
答案 0 :(得分:6)
var str = "eyJpc3MiOiJodHRwczovL2lkZW50aXR5LXN0YWdpbmcuYXNjZW5kLnh5eiIsImF1ZCI6Imh0dHBzOi8vaWRlbnRpdHktc3RhZ2luZy5hc2NlbmQueHl6L3Jlc291cmNlcyIsImNsaWVudF9pZCI6IjY5OTRBNEE4LTBFNjUtNEZFRC1BODJCLUM2ODRBMEREMTc1OCIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJzdWIucmVhZCIsImRhdGEud3JpdGUiLCJkYXRhLnJlYWQiLCJhbGcuZXhlY3V0ZSJdLCJzdWIiOiIzNzdjMDk1Yi03ODNiLTQ3ZTctOTdiMS01YWVkOThjMDM4ZmMiLCJhbXIiOiJleHRlcm5hbCIsImF1dGhfdGltZSI6MTQwNzYxNTUwNywiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvMDg0MGM3NjAtNmY3Yi00NTU2LWIzMzctOGMwOTBlMmQ0NThkLyIsIm5hbWUiOiJwa3NAYXNjZW5kLnh5eiIsImV4cCI6MTQwNzgzNjcxMSwibmJmIjoxNDA3ODMzMTExfQ";
int mod4 = str.Length % 4;
if (mod4 > 0)
{
str += new string('=', 4 - mod4);
}
在c#
中解决了这个问题答案 1 :(得分:2)
使用 javascript的window.btoa 函数在Javascript前端UI中以Base 64格式对字符串进行编码。要在C#中解码相同的字符串(相当于 javascript的window.atob 函数),请参阅以下代码。
(很可能你试图回发数据(在大多数情况下为HTML,因为它需要btoa编码以确保最佳兼容性))回到控制器)
string base64Encoded = "YmFzZTY0IGVuY29kZWQgc3RyaW5n";
string base64Decoded;
byte[] data = System.Convert.FromBase64String(base64Encoded);
base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data);
Console.WriteLine(base64Decoded)
查看其工作样本