如何正确使用UrlEncode和Decode
所以我有一个文件,我上传到azure blob存储:
C:\ test文件夹\ A + B \ testfile.txt
和两个扩展方法,帮助编码我的路径,以确保它被赋予有效的azure存储blob名称
public static string AsUriPath(this string filePath) { return System.Web.HttpUtility.UrlPathEncode(filePath.Replace('\\', '/')); } public static string AsFilePath(this string uriPath) { return System.Web.HttpUtility.UrlDecode(uriPath.Replace('/', '\\')); }
因此,当上传文件时,我将其编码为AsUriPath
并获取名称test%20folder\A+B\testfile.txt
但是当我尝试将其作为文件路径返回时,我得到test folder\AB\testfile.txt
,这显然不是相同( +
已被删除)
使用UrlEncode和UrlDecode确保您获得与最初编码相同的信息的正确方法是什么?
如果你使用WebUtility.UrlEncode
而不是HttpUtility.UrlPathEncode
它的工作原理
如果您查看HttpUtility.UrlPathEncode上的文档,您会看到它指出:
不使用; 仅用于浏览器兼容性。 使用UrlEncode。
我编写了一个简单的例子,可以粘贴到控制台应用程序中(你需要引用System.Web程序集)
static void Main(string[] args) { string filePath = @"C:\test folder\A+B\testfile.txt"; var encoded = WebUtility.UrlEncode(filePath.Replace('\\', '/')); var decoded = WebUtility.UrlDecode(encoded.Replace('/', '\\')); Console.WriteLine(decoded); }
在这个.NET Fiddle上运行它
使用System.Uri类正确编码路径: MSDN System.Uri
在您的路径上尝试以下操作并使用调试器检查:
var myUri = new System.Uri("http://someurl.com/my special path + is this/page?param=2"); var thePathAndQuery = myUri.PathAndQuery; var theAbsolutePath = myUri.AbsolutePath; var theAbsoluteUri = myUri.AbsoluteUri;
- 502在azure’网站’内请求付款服务
- 如何通过端口80向Azure Service Bus发送消息?
- 在Azure函数中初始化AutoMapper
- 使用AzureReader2插件的Azure ImageResizer没有resize
- Azure托管服务总线:“X.509证书CN = servicebus.windows.net不在受信任的人员商店中。”
- DocumentDB TransientFaultHandling最佳实践
- Azure Fluent API – AppServicePlanOperations.ListMetricsWithHttpMessagesAsync返回InternalServerError
- 连接Azure Search后使用Document DB的好处
- Azure通知中心社交网络方案中的最佳实践