如何正确使用UrlEncode和Decode [英] How to correctly use UrlEncode and Decode

查看:781
本文介绍了如何正确使用UrlEncode和Decode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个文件上传到azure blob存储:


C:\test folder\A + B \\ \\ testfile.txt


和两个扩展方法,有助于编码我的路径,以确保它被赋予一个有效的天蓝色存储blob名称< public static String AsUriPath(this string filePath)
{
return System.Web.HttpUtility.UrlPathEncode(filePath .Replace('\\\','/'));
}
public static string AsFilePath(此字符串uriPath)
{
返回System.Web.HttpUtility.UrlDecode(uriPath.Replace('/','\\' ));
}

所以当上传文件时我编码它 AsUriPath 并获取名称 test%20folder\A + B\testfile.txt
但是当我尝试把它作为一个文件路径我得到 test folder\AB\testfile.txt 这显然是不一样的( + 有已被删除)



使用UrlEncode和UrlDecode的正确方法是确保您得到与原始编码相同的信息解码?

解决方案

如果您使用 WebUtility.UrlEncode 而不是 HttpUtility.UrlPathEncode



如果您查看 docs on HttpUtility.UrlPathEncode ,你会看到它说明:



< blockquote>

不要使用;仅用于浏览器兼容性。使用UrlEncode。


我编写了一个简单的例子,可以粘贴到控制台应用程序中(您需要参考System.Web程序集)

  static void Main(string [] args)
{
string filePath = @C:\test folder\A + B\testfile.txt;
var encoded = WebUtility.UrlEncode(filePath.Replace('\\','/'));
var decoding = WebUtility.UrlDecode(encoded.Replace('/','\\'));
Console.WriteLine(解码);
}

在这里运行这个。NET Fiddle


So I have a file I am uploading to azure blob storage:

C:\test folder\A+B\testfile.txt

and two extension methods that help encode my path to make sure it is given a valid azure storage blob name

    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('/', '\\'));
    }

So when upload the file I encode it AsUriPath and get the name test%20folder\A+B\testfile.txt but when I try to get this back as a file path I get test folder\A B\testfile.txt which is obviously not the same (the + has been dropped)

What's the correct way to use UrlEncode and UrlDecode to ensure you will get the same information decoded as you originally encoded?

解决方案

It works if you use WebUtility.UrlEncode instead of HttpUtility.UrlPathEncode

If you check out the docs on HttpUtility.UrlPathEncode you'll see that it states:

Do not use; intended only for browser compatibility. Use UrlEncode.

I've coded up a simple example which can be pasted into a console app (you'll need to reference the System.Web assembly)

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);
}

Run it here at this .NET Fiddle

这篇关于如何正确使用UrlEncode和Decode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆