Tim Liberty Tim Liberty - 2 months ago 12
ASP.NET (C#) Question

Asp.Net MVC routing not accepting & in the route

I have a default Asp.Net route as follows:

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


Nothing to special in it.

And I have my super simple default action in Home Controller:

public ActionResult Index(string id)
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

return View();
}


I can type the URL: http://localhost:12143/Home/Index/HanselandCratel

and it works fine but when I type in

http://localhost:12143/Home/Index/Hansel&Cratel

it doesn't

I understand & has to be encoded but when I type in:

http://localhost:12143/Home/Index/Hansel%26Cratel

it still doesn't work I get this error:

A potentially dangerous Request.Path value was detected from the client (&).


I am aware of setting this in web.config:

<httpRuntime targetFramework="4.5" requestPathInvalidCharacters="" />


but I am afraid I will have to sacrifice security when I do that.

Is there any other alternative to this? Perhaps any setting in Asp.Net?

Answer

I am aware of setting this in web.config: <httpRuntime targetFramework="4.5" requestPathInvalidCharacters="" />

Do not do it, you're removing all the protection given by this request validation rule. If you want to allow & character then leave all the others in-place:

<httpRuntime requestPathInvalidCharacters="&lt;,&gt;,*,%,:,\,?" />

but I am afraid I will have to sacrifice security when I do that.

In this way & will be allowed in your request URLs. Be careful to properly validate all input parameters and to, eventually, escape them as required. Note that it should be done also with original rule in-place...

You may re-include also other characters but I'd suggest to do it only if required. You may also add new ones: sometimes I have text IDs as parameters (for AJAX GET requests) and even if I'm sure I won't ever build a SQL command concatenating strings...I usually add ' (and few others).

Is there any other alternative to this? Perhaps any setting in Asp.Net?

Yes, you may go back to .NET 2.0 rules but I see no reason to do it...

Comments