标准化 URI 以使其与 MakeRelativeUri 一起正常工作

发布于 2024-08-13 14:26:25 字数 461 浏览 1 评论 0原文

Dim x AS New URI("http://www.example.com/test//test.asp")
Dim rel AS New URI("http://www.example.com/xxx/xxx.asp")
Console.Writeline(x.MakeRelativeUri(rel).Tostring())

这里的输出是:

../../xxx/xxx.asp

看起来正确的几乎所有 Web 服务器都会将以下两项作为同一请求处理:

http://www.example.com/test//test.asp
http://www.example.com/test/test.asp

修复此行为的最佳方法是有任何 API 可以执行此操作,还是应手动创建新的 URI 并删除所有 / / 在路径中?

Dim x AS New URI("http://www.example.com/test//test.asp")
Dim rel AS New URI("http://www.example.com/xxx/xxx.asp")
Console.Writeline(x.MakeRelativeUri(rel).Tostring())

In here output is:

../../xxx/xxx.asp

Which looks correct almost all web servers will process the two of the following as same request:

http://www.example.com/test//test.asp
http://www.example.com/test/test.asp

What's the best way to fix this behaviour is there any API to do this, or shall manually create a new URI and remove all // in the path?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

路弥 2024-08-20 14:26:25

看来,在 LocalPath 部分中用一个斜杠替换所有多斜杠是最好的解决方案。即使将 URL 传递给 ASP.net,IIS 也会这样做。

下面的代码就可以解决问题。

x = new Uri(string.Format("{0}://{1}:{2}{3}{4}", x.Scheme, x.Host, x.Port, Regex.Replace(x.LocalPath, @"(?<!\:)/{2,}", "/"), x.Query));

It seems that replacing all multi-slashes with one slash in LocalPath portion is the best solution. IIS does so even when passing URL to ASP.net.

Following code will do the trick.

x = new Uri(string.Format("{0}://{1}:{2}{3}{4}", x.Scheme, x.Host, x.Port, Regex.Replace(x.LocalPath, @"(?<!\:)/{2,}", "/"), x.Query));
好菇凉咱不稀罕他 2024-08-20 14:26:25

首先,您的代码不是 C# 而是 VB,因此标签是错误的。

您可以改用此代码吗?它给出了“正确”的 url,因为 // 位于 baseuri 中并且将被丢弃?

var x2 = new Uri(x, rel);

或者在 url 中获取 ../ 回溯很重要吗?

MakeRelativeUri 函数根据 RFC 确实正确,但根据正常约定它失败。我建议您自己规范化 url,或者如果可能的话使用我上面的示例。

x = new Uri(Regex.Replace(x.OriginalString, "[^:]//", "/"));

First off, your code is not C# but VB, so tags are wrong.

Can you use this code instead, which gives the "correct" url since the // are in the baseuri and will be discarded?

var x2 = new Uri(x, rel);

Or is it important to get the ../ backtracking in the url?

The MakeRelativeUri function does correct according to the RFC, but it fails according to normal convention. I would suggest you normalize the url yourself, or use my example above if possible.

x = new Uri(Regex.Replace(x.OriginalString, "[^:]//", "/"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文