1

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.

Martin Smellworse
  • 1,702
  • 3
  • 28
  • 46
  • 2
    Possible duplicate of [URL Routing, Image Handler & "A potentially dangerous Request.Path value"](http://stackoverflow.com/questions/14475913/url-routing-image-handler-a-potentially-dangerous-request-path-value) – Clint B Jul 15 '16 at 11:16

1 Answers1

4

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")
              ;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Thank you for your reply. I am finding that HttpUtility.UrlEncode is turning the ampersand into %26 - which is leading to a 'file not found' message – Martin Smellworse Jul 15 '16 at 11:42
  • which is the version of IIS server where you have hosted your website? Can you please check if URL rewrite module is installed in IIS or not? URL rewrite module does the work of converting the encoded URL back to normal. If it is missing you will get 404 resource not found error. – RBT Jul 15 '16 at 12:08
  • Have a look at this thread - http://stackoverflow.com/questions/4604392/symbol-problem-in-url-in-iis-7-x – RBT Jul 15 '16 at 12:10