简体   繁体   中英

Handling an ampersand in a url

I have a hyperlink on a .aspx page

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

On the code behind page I have:

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

This generates a url that looks like: http://myDomain/myEmailAttachments/1436/Picture%20of%20Jim&John.jpg

This causes a message to be shown: A potentially dangerous Request.Path value was detected from the client (&).

I have tried using Server.Urlencode. This produces a url that looks like ...

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

This causes the same message to be shown: A potentially dangerous Request.Path value was detected from the client (&).

If I have a file called ...

Picture of Jim&John.jpg

... How can I get it into a hyperlink so it will actually go and get the file? Thank you for any help.

That is because you don't want to HTML encode ( HttpUtility.HtmlEncode ), but URL encode ( HttpUtility.UrlEncode ). Then the %26 will be rewritten as &amp; which is the correct format for an URL. That will prevent ASP.NET see it as potentially malicious.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM