Getting "A potentially dangerous Request.Path value was detected from the client (&)" - asp.net-mvc

I've got a legacy code issue that requires that I support random URLs as if they were requests for the home page. Some of the URLs have characters in them that generate the error "A potentially dangerous Request.Path value was detected from the client (&)". The site is written with ASP.Net MVC 3 (in C#) and is running on IIS 7.5.
Here's an example URL...
http://mywebsite.example/Test123/This_&_That
Here's how I have my catch-all route setup (I have other routes to catch specific pages)...
routes.MapRoute(
"Default", // Route name
"{garb1}/{garb2}", // URL with parameters
new { controller = "Website", action = "Home", garb1 = UrlParameter.Optional, garb2 = UrlParameter.Optional } // Parameter defaults
);
I've added the following things to my web.config file...
<configuration>
<system.web>
<pages validateRequest="false" />
<httpRuntime requestValidationMode="2.0" />
</system.web>
<configuration>
I've also Added the ValidateInput attribute to the action that should be catching the urls...
public class WebsiteController : Controller
{
[ValidateInput(false)]
public ActionResult Home()
{
return View();
}
}
But I'm still getting the error. Any ideas why? Did I miss something? Right now I'm just running on my local dev server (I haven't tried these fixes in production yet).

While you could try these settings in config file
<system.web>
<httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
I would avoid using characters like '&' in URL path replacing them with underscores.

I have faced this type of error.
to call a function from the razor.
public ActionResult EditorAjax(int id, int? jobId, string type = ""){}
solved that by changing the line
from
<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" />
to
<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />
where my route.config is
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
);

If you want to allow Html tags only for few textbox in mvc
You can do one thing
in controller
[ValidateInput(false)]
public ActionResult CreateNewHtml() //view
{
return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateNewHtml(cbs obj)//view cbs is database class
{
repo.AddHtml(obj);
return View();
}

We were getting this same error in Fiddler when trying to figure out why our Silverlight ArcGIS map viewer wasn't loading the map.
In our case it was a typo in the URL in the code. There was an equal sign in there for some reason.
http:=//someurltosome/awesome/place
instead of
http://someurltosome/awesome/place
After taking out that equal sign it worked great (of course).

Check the below lines are present in your web.config file
<system.web>
<httpRuntime requestPathInvalidCharacters="" />
</system.web>

Related

Using dot in URL

I have the following route in RouteConfig.cs:
routes.MapRoute(
"MyLegacyRoute",
"Content/bootstrap.css",
new { controller = "Legacy", action = "GetLegacyUrl", legacyUrl = "someUrl" });
~/Content/bootstrap.css exists and rather than display its content when I navigate to http://localhost:27541/Content/bootstrap.css, I want to hit the GetLegacyUrl action in the Legacy controller.
I have added this to Web.config:
<system.webServer>
<handlers>
<add name="UrlRoutingHandler" path="/Content/*" verb="GET" type="System.Web.Routing.UrlRoutingHandler" />
...
and
<system.web>
<httpRuntime targetFramework="4.5" relaxedUrlToFileSystemMapping="true"/>
...
However when I access http://localhost:27541/Content/bootstrap.css I get this error:
Server Error in '/' Application.
Cannot create an abstract class.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: Cannot create an abstract class.
My controller looks like this:
public class LegacyController : Controller
{
public ActionResult GetLegacyUrl(string legacyUrl)
{
return View((object)legacyUrl);
}
}
My view (GetLegacyUrl.cshtml) looks like this:
#model string
#{
ViewBag.Title = "GetLegacyUrl";
Layout = null;
}
<h2>GetLegacyUrl</h2>
The URL requested was #Model
I am trying to do this just so I can learn more about routing.
What can I do to successfully use this route?
I got it to work by putting this in RouteConfig.cs:
routes.RouteExistingFiles = true;
And by making the preCondition value an empty string:
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
in this file: C:\Users\user.name\Documents\IISExpress\config\applicationhost.config
I found the answer on pg 99/115 chapter 16 in Adam Freeman's Pro ASP.NET MVC5 book.
I also removed the handler I added in the Web.config and removed the relaxedUrlToFileSystemMapping="true" since that doesn't work in MVC5.

Using a route to return 408 on a specific file name request

We have an issue whereby Outlook is misbehaving because it is attempting to read an autodiscover.xml on our domain, specifically https://example.com/autodiscover/autodiscover.xml.
The email host says that we should configure the websitefirewall to return a timeout error. However, the site is hosted on Azure, and I don't see any option to do that.
Therefore, I was wondering if this could be done in MVC? I tried the following:
public class AutoDiscoverController : Controller
{
[Route("autodiscover/autodiscover.xml")]
public ActionResult Index()
{
return new HttpStatusCodeResult(HttpStatusCode.RequestTimeout);
}
}
...but it doesn't work; I see a 404 page instead. A breakpoint on the method also never gets hit.
Is it possible to create a route that mimics a non-existent file to return the timeout error?
Duplicate question update
There is a similar question at Dots in URL causes 404 with ASP.NET mvc and IIS. However, this question differs in that:
The answer doesn't work in MVC5
I cannot create a rule to recognise a trailing slash in the URL, because Outlook is generating the URL and I have no control over that
What else I've tried...
In RouteConfig, I defined a custom route. It doesn't work; the route never gets hit.
routes.MapRoute(
name: "AutoDiscover",
url: "autodiscover/autodiscover.xml",
defaults: new { controller = "AutoDiscover", action = "Index" });
As above, but using url: "autodiscover/*"
routes.IgnoreRoute("autodiscover.xml");
Defined a Route attribute on the controller itself, then enable routes.MapMvcAttributeRoutes();
I found an answer, thanks to Rick Strahl's answer here, and related blog post.
For some reason, defining a route in the RouteConfig never hits, but doing it at controller level does work. However, an additional step is needed, as pointed out by Nkosi to get it to work.
1. Enable MVC Attribute Routing
This wires up the routing attributes at controller-level (done in the next step)
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // <-- Added this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
2. Add the Route as an attribute
public class AutoDiscoverController : Controller
{
[Route("autodiscover/autodiscover.xml")]
public ActionResult Index()
{
return new HttpStatusCodeResult(HttpStatusCode.RequestTimeout);
}
}
3. Configure a route based on specific files in web.config
I believe this forces MVC to take over what IIS would usually handle (as XML is considered a "static" file).
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
<!-- Added this line -->
<add name="AutoDiscoverXmlFileHandler" path="autodiscover.xml" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
</handlers>
</system.webServer>
Result

Adding Sitemap.xml on MVC5 doens't work on Godaddy

I just want my MVC5 Site hosted on godaddy to handle the sitemap.xml file.
(mysite.com/sitemap.xml) .
I've seen and followed this post: MVC: How to route /sitemap.xml to an ActionResult?
Added Handler on Web.Config
<add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
I added a route for my sitemap.xml file:
routes.MapRoute(
name: "Sitemap",
url: "sitemap.xml",
defaults: new { controller = "Home", action = "SiteMap", id = UrlParameter.Optional }
);
Added the corresponding View and it's controller
3.1 (SiteMap.cshtml on \Views\Home) with some xml contento
3.2 A Home Controller for that:
public ActionResult SiteMap()
{
return View();
}
(with just sample xml text)
While running Visual Studio, I can see the localhost:xxxx/sitemap.xml mapping.
I upload it to Godaddy, and then I just get a 404 error (accesing mysite.com/sitemap.xml)
Any clue?
Any step I'm missing?
Thanks for your help.
PnP

ASP.NET MVC 5 custom route does not work

I'm trying for hours to get my custom route to work. I always get a 404 and can't see what I'm doing wrong.
The URL scheme I'm trying to get: /Download/fd39kssdf/myfile.zip.
This is the route, defined before the default route:
routes.MapRoute(
name: "Download",
url: "Download/{hash}/{name}",
defaults: new { controller = "Download", action = "Index"}
);
This is the code in the controller named "DownloadController":
public ActionResult Index(string hash, string name)
{
}
I have tried adding the parameters to the route with UrlParameter.Optional and "", but neither does work.
Where is the error?
Thank you!
You problem is that the IIS has file extensions mapped directly, so your request isn't even being passed over to the ASP.NET handler for processing. It's actually looking for a myfile.zip in that directory, which doesn't exist giving you the 404 error.
<configuration>
<system.webServer>
<handlers>
<add name="Download-MVC"
path="/Download/*"
verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>

After adding ELMAH and changing elmah.mvc.route the old route is still available

I've added ELMAH to my ASP.NET MVC 4 .Net 4 web application.
The intergration was simple and it works well.
I've changed the "elmah.mvc.route" value in the app settings of my web.config to an "Admin/SiteLog" route - the elmah log is displayed at this route now
But, it is also still shown at "/elmah" for some reason (with no css styling, but same content).
How can I disable the default elmah route?
The integration was made using Elmah.MVC nuget package
I've just been working through this problem myself and the latest version seems to have a couple of app settings that works nicely enough for this.
<add key="elmah.mvc.IgnoreDefaultRoute" value="true" />
<add key="elmah.mvc.route" value="admin/elmah" />
It's probably also worth being aware of the others so take a look after a default install.
<add key="elmah.mvc.disableHandler" value="false" />
<add key="elmah.mvc.disableHandleErrorFilter" value="false" />
<add key="elmah.mvc.requiresAuthentication" value="false" />
<add key="elmah.mvc.allowedRoles" value="*" />
<add key="elmah.mvc.allowedUsers" value="*" />
This happens because the default route (assuming you have one) will still match to Elmah.Mvc.ElmahController.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
The "{controller}" portion of the route will find a matching controller whether you want it to or not. This is obviously problematic in this case.
You can add constraints on your routes by using IRouteConstraint, outlined here. The NotEqual constraint is actually pretty useful.
using System;
using System.Web;
using System.Web.Routing;
public class NotEqual : IRouteConstraint
{
private string _match = String.Empty;
public NotEqual(string match)
{
_match = match;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return String.Compare(values[parameterName].ToString(), _match, true) != 0;
}
}
So then exclude ElmahController from the default route by using the following.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = new NotEqual("Elmah") });
This will make requests for "/elmah" return a 404.
You can specify the location by updating the path in the httpHandlers section of the web.config
<httpHandlers>
<add verb="POST,GET,HEAD" path="admin/elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
</httpHandlers>

Resources