处理 url 中的与号

本文关键字:url 处理 | 更新日期: 2023-09-27 17:57:02

我在.aspx页面上有一个超链接

<asp:HyperLink ID="hlTest" runat="server" NavigateUrl="#">Test Link</asp:HyperLink>

在代码隐藏页面上,我有:

string link = "http://myDoman/myEmailAttachments/1436/" + HttpUtility.HtmlEncode("Picture of Jim&John.jpg");
hlTest.NavigateUrl = link;

这将生成如下所示的 URL:http://myDomain/myEmailAttachments/1436/Picture%20of%20Jim&John.jpg

这会导致显示一条消息:从客户端检测到具有潜在危险的 Request.Path 值 (&)。

我尝试过使用Server.Urlencode。这将生成一个看起来像

...

http://myDomain/myEmailAttachments/1436/Picture+of+Jim%26John.jpg

这会导致显示相同的消息:从客户端检测到具有潜在危险的 Request.Path 值 (&)。

如果我有一个名为...

吉姆和约翰的照片.jpg

。我怎样才能把它放到超链接中,这样它才能真正去获取文件?感谢您的任何帮助。

处理 url 中的与号

那是因为你不想HTML编码(HttpUtility.HtmlEncode),而是URL编码(HttpUtility.UrlEncode)。然后%26将被重写为 &amp;这是 URL 的正确格式。这将防止 ASP.NET 将其视为潜在的恶意。

string link = "http://myDoman/myEmailAttachments/1436/"
              + HttpUtility.UrlEncode("Picture of Jim&John.jpg")
              ;