Javascript atob(str)在c#中等效

我这样做了:

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控制台:

 atob("eyJpc") "{"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}" 

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

在c#中解决了

使用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) 

您可以在https://dotnetfiddle.net/abxwSw上查看其工作示例