我想base64编码数据把它放在一个URL中,然后在我的HttpHandler中解码它.
我发现Base64编码允许使用'/'字符,这会弄乱我的UriTemplate匹配.然后我发现维基百科有一个"修改过的Base64 for URL"的概念:
存在修改的URL变体Base64,其中不使用填充'=',标准Base64的'+'和'/'字符分别替换为' - '和'_',因此使用URL编码器/解码器不再需要,并且对编码值的长度没有影响,保留相同的编码形式,以便在关系数据库,Web表单和对象标识符中使用.
使用.NET我想修改我当前的代码,从基本的base64编码和解码到使用"修改的base64 for URL"方法.有没有人这样做过?
为了解码,我知道它开头是这样的:
string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/');
// Append '=' char(s) if necessary - how best to do this?
// My normal base64 decoding now uses encodedText
Run Code Online (Sandbox Code Playgroud)
但是,我需要在结尾处添加一个或两个'='字符,这看起来有点复杂.
我的编码逻辑应该更简单一些:
// Perform normal base64 encoding
byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText);
string base64EncodedText = Convert.ToBase64String(encodedBytes);
// Apply URL variant
string base64UrlEncodedText = base64EncodedText.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
Run Code Online (Sandbox Code Playgroud)
我已经看到Guid to Base64用于URL StackOverflow条目,但是它具有已知长度,因此它们可以硬编码最后所需的等号数.
我想在C#中实现Base64 URL安全编码.在Java中,我们有一个公共Codec库,它为我提供了一个URL安全编码字符串.如何使用C#实现相同的目标?
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes("StringToEncode");
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
Run Code Online (Sandbox Code Playgroud)
上面的代码将它转换为Base64,但它填充==.有没有办法实现URL安全编码?
使用.NetCore 1.1.2.
通过Azure Search SDK成功获取搜索结果后,我正在尝试解码metadata_storage_path值.我见过有人说要在.NET中使用HttpServerUtility.UrlTokenDecode或者在这里看到其他语言中的等价物.
那么问题就变成了,HttpServerUtility.UrlTokenDecode的.NetCore中的等价物是什么?附:
var pathEncoded = "aHR0cHM6Ly9mYWtlZC5ibG9iLmNvcmUud2luZG93cy5uZXQvcGRmYmxvYnMvYW5udWFsX3JlcG9ydF8yMDA5XzI0NTU20";
Run Code Online (Sandbox Code Playgroud)
我尝试过以下方法:
var pathbytes = Convert.FromBase64String(pathEncoded);
//Throws System.FormatException "Invalid length for a Base-64 char array or string."
Run Code Online (Sandbox Code Playgroud)
和
var pathbytes = WebEncoders.Base64UrlDecode(pathEncoded);
//Throws System.FormatException - "TODO: Malformed input."
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我切断了pathEncoded中的最后一个字符,一切都运行正常...用Microsoft.AspNetCore 1.1.2处理这种情况的正确方法是什么?
c# azure azure-cognitive-search asp.net-core azure-search-.net-sdk