2
votes

I'm having a fairly common issue with ASP.NET MVC 5 where it throws an exception on invalid URL characters, such as & and %.

I've tried a lot of different suggestions from other stack overflow questions, like here and here. However, adding this to my Web.config doesn't work:

<system.web>
    <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,%,:,\,?"
                 requestValidationMode="2.0"/>
</system.web>  

Nor does adding [HttpValidate(false)] above my controller methods.

I found this gem while searching for a solution and it looked really promising, but even that doesn't work. The url requests aren't being changed with the code from that site and it makes me wonder if the problem occurs before ASP.net even gets a chance to act.

I'm trying to avoid manually encoding all my requests, but if that's what I have to do then I guess I have no choice.

Here's my stack trace if it helps:

[HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (&).]

System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +9693412 System.Web.PipelineStepManager.ValidateHelper(HttpContext context) +53

1

1 Answers

1
votes

I've encountered that error in a Web-Form application, it is often caused by special characters being passed to a Controller. The simplest resolution, to ensure that your data is being properly encoded before hitting your Controller. That would be the safest approach, however if you want a quick and dirty approach you can loosen the security a bit to the Page / View through your web.config.

<!-- Example: 'Web-Config' -->
<location path="test.aspx">
  <system.web>
    <httpRuntime requestValidationMode="2.0" />
  </system.web>
</location>

The above does the following:

In either case, you must make two changes in the Web.config file. The first change is to set the requestValidationMode attribute of the httpRuntime element to "2.0". This setting makes request validation occur later in the sequence of request processing events. The setting is required for applications that use ASP.NET 4 and later, because as of ASP.NET 4, request validation takes place earlier in the request life cycle than it did in previous versions of ASP.NET.

Otherwise you could simply use the:

HttpUtility.HtmlDecode("...");
HttpUtility.HtmlEncode("...");

Purpose of above:

If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as < and > for HTTP transmission.

You can also lookup UrlEncode and UrlDecode.