在 .NET 中创建 Uri 会自动对传递的字符串中的所有参数进行 url 解码
假设我想从以下字符串创建一个 Uri 对象:
string url = @"http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com";
Uri uri = new Uri(url, UriKind.Absolute);
预期结果是:
http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com
获得:
http://someserver.com/?param1=1&url=http://www.otherserver.com
在许多允许创建 Uri 的相关方法中注意到相同的行为:Uri.TryCreate、UriBuilder.Uri 等。
我如何获得 Uri保留初始编码参数?
Suppose I want to create an Uri object from the following string:
string url = @"http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com";
Uri uri = new Uri(url, UriKind.Absolute);
Expected result would be:
http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com
Obtained:
http://someserver.com/?param1=1&url=http://www.otherserver.com
The same behavior is noticed in many related methods that allow Uri creation: Uri.TryCreate, UriBuilder.Uri, etc.
How would I get an Uri that preserve initial encoded parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 .NET4 中,您可以通过配置禁用某些方案的 Uri 压缩:
请注意,禁用默认行为会产生安全隐患。
In .NET4 you can disable Uri compaction for certain scheme via a configuration:
Note that there are security implications related to disabling of the default behaviour.
您是如何“获取”URL 的?如果我在 Visual Studio 中将鼠标悬停在它上面,它确实会显示解码后的 URL。
但每当我通过
AbsoluteUri
属性访问它时,它都会显示编码后的 URL。How did you "obtain" the URL? If I hover my mouse over it in Visual Studio, it indeed shows the decoded URL.
But whenever I access it through the
AbsoluteUri
property, it shows the encoded URL.此行为已记录:
因此,一种解决方法可能是暂时使用自定义方案(例如
leavemealone://
)来构造 URL 对象(可能通过UriBuilder
?)。This behavior is documented:
So one workaround might be temporarily using a custom scheme (e.g.
leavemealone://
) to construct the URL objects (possibly throughUriBuilder
?).就我而言,我通过返回 UriBuilder 类的 ToString() 方法而不是使用同一类的 Uri 属性来解决它。
In my case I solved it by returning ToString() method of UriBuilder class instead of using Uri property of the same class.
我推荐使用 Flul 库。它允许流畅、正确地构建和分析 URI。看看他们的例子。 https://flurl.dev/docs/ Fluent-url/
它以 NuGet 形式提供包裹。你不需要 HTTP 的东西
I recommend using the library Flurl. It allows a fluent and correct build and analysis of URIs. See their examples. https://flurl.dev/docs/fluent-url/
It is available as NuGet package. You don't need the HTTP-Stuff