.net 在不使用HttpUtility的情况下解码转义的URL,UrlDecode

balp4ylt  于 2023-04-22  发布在  .NET
关注(0)|答案(9)|浏览(136)

是否有函数可以将转义的URL字符串转换为未转义的形式?System.Web.HttpUtility.UrlDecode()可以完成这项工作,但我不想添加对System.Web.dll的引用。由于我的应用程序不是Web应用程序,因此我不想添加仅使用程序集中函数的依赖项。

**UPDATE:**查看Rick Strahl's blog post相同问题。

c90pui9n

c90pui9n1#

**编辑:使用静态方法Uri.UnescapeDataString()**解码您的URL:

  • 编码:* http%3a%2f%2fwww.google.com%2fsearch%3fhl%3den%26q%3dsomething%20%2323%26btnG%3dGoogle%2bSearch%26aq%3df%26oq%3d
  • 解码:* http://www.google.com/search?hl=en&q=something #23&btnG=Google+Search&aq=f&oq=
ovfsdjhp

ovfsdjhp2#

如果您使用的是.NET 4.0或更高版本,则可以使用WebUtility.UrlDecode,它可以与客户端配置文件一起工作,还可以正确处理加号。

wfveoks0

wfveoks03#

Re not loading System.Web.dll -正如其他人所指出的,除非你知道你需要处理可能没有它的客户端(“客户端配置文件”,“紧凑框架”,“微框架”,“silverlight”),否则不值得兴奋。
太空;不会太多;请注意.NET程序集是在逐个方法的基础上进行JIT的,因此仅使用几个方法不会产生任何显著的开销。
真实的的问题(IMO)是您对客户端具有System.Web.dll的信心程度;如果你对他们使用完整的框架感到高兴,那就去做吧。

guicsvcw

guicsvcw4#

@史密斯
我遇到了保存问题。没有更改或只是进一步混乱。
在测试了很多东西之后,我注意到一个测试字符串确实解码了。最终我不得不创建一个新的空字符串,将其值设置为编码字符串,然后在新字符串上运行WebUtility.HtmlDecodeUri.UnescapeDataString。出于某种原因,我不得不按照我提到的顺序运行解码和unescape。奇怪。
我用这个解决了问题。

Dim strEncoded as string="http%3a%2f%2fwww.google.com%2fsearch%3fhl%3den%26q%3dsomething%20%2323%26btnG%3dGoogle%2bSearch%26aq%3df%26oq%3d"

Dim strDecoded as string = ""
strDecoded = strEncoded
strDecoded = WebUtility.HtmlDecode(strDecoded)
strDecoded = Uri.UnescapeDataString(strDecoded)
lnxxn5zx

lnxxn5zx5#

Microsoft ACE团队在Anti-XSS library中有一个扩展(更好)的decode版本。但是我不确定它是否只是通过。
(老实说,我不明白你为什么那么担心对System.web.dll的依赖)

uklbhaso

uklbhaso6#

你已经对.NET框架、CLR埃塔尔有了巨大的依赖,所以,事实上,你已经对System.Web.DLL有了间接的依赖;如果你的应用程序不在本地机器上,它就不能运行。
你担心内存问题?你有内存问题吗?如果你有内存问题,以至于你不能加载几KB的DLL到你的应用程序的内存中,那么你为什么要编码.NET?或者你只是过早地优化?
所以别担心

mwg9r5ms

mwg9r5ms7#

只需要稍微理解一下为什么不同。一个转换成大写,一个转换成小写。所以解码是特定于编码类型的。

System.Net.WebUtility(内部)+ 65

private static char IntToHex(int n)
{
    if (n <= 9)
        return (char) (n + 48);
    else
        return (char) (n - 10 + 65);
}

System.Web.Util.HttpEncoderUtility(内部)-+ 97

public static char IntToHex(int n)
{
    if (n <= 9)
        return (char) (n + 48);
    else
        return (char) (n - 10 + 97);
}

示例

var test1 = WebUtility.UrlEncode("http://www.test.com/?param1=22&param2=there@is<a space");
var test2 = HttpUtility.UrlEncode("http://www.test.com/?param1=22&param2=there@is<a space");

回复

test1 -> http%3A%2F%2Fwww.test.com%2F%3Fparam1%3D22%26param2%3Dthere%40is%3Ca+space
test2 -> http%3a%2f%2fwww.test.com%2f%3fparam1%3d22%26param2%3dthere%40is%3ca+space

More information....

vpfxa7rd

vpfxa7rd8#

在Android这个固定的问题,我花了几个小时才弄清楚,我希望我现在节省你的时间

val objectRequest = GetObjectRequest(s3Uri.bucket, S3HttpUtils.urlDecode(s3Uri.key))
xytpbqjk

xytpbqjk9#

System.Net.WebUtility.HtmlDecode也在.NET 4.0客户端配置文件上运行。

相关问题