Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use MVC5 attribute-based routes with a dot/period in them?

I have basically an out-of-the box MVC 5.2 app, with attribute-based routes enabled (calling routes.MapMvcAttributeRoutes(); from the provided RouteConfig.RegisterRoutes(RouteCollection routes) method).

The following is in HomeController:

    [Route("hello.txt")]
    [Route("hellotxt-testing")]
    public ActionResult ShowFile()
    {
        return Content("Hello world");
    }

I can successfully access /hellotxt-testing (proving attribute-based routing is working correctly):

accessing /hellotxt-testing

But I get a 404 page if I access /hello.txt:

accessing /hello.txt

In contrast to when I go to /hello404, where I get a different 404 page:

accessing /hello404

I am guessing that the second 404 page is from ASP.NET, while the first is from IIS which isn't even passing the request to ASP.NET?

What do I do to ensure that I can ensure ASP.NET gets these URLs that have periods in them? Are there other 'special' characters that would also cause a problem?

like image 685
gregmac Avatar asked Dec 25 '22 00:12

gregmac


1 Answers

The difference between errors you see is because when you try to access /hello.txt IIS tries to reach the static resource file located on the server, on the other hand /hello404 is just an unknown route so 404 is thrown.

To ensure that I am right try to add slash at the end and access /hello.txt/ you should now get 404 error.

There are several ways to resolve this problem:

First you can try

<modules runAllManagedModulesForAllRequests="true">

but this option called RAMMFAR hurts the performance of web application. and has other consequences.

Second you can create rule for IIS URL REWRITE to always add trailing slash to each incoming URL's

Third go with Dots in URL causes 404 with ASP.NET mvc and IIS and

<add name="ApiURIs-ISAPI-Integrated-4.0"
     path="/people/*"
     verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
     type="System.Web.Handlers.TransferRequestHandler"
     preCondition="integratedMode,runtimeVersionv4.0" />

but you did not like this.

Fourth try to create custom http handler to add trailing slash to all requests like in this topic Add a trailing slash at the end of each url?


I would go with second option if you need this to work in many places in your application.

But I think the best one is third. Such url's with dots are not user friendly and are against SEO rules. You should avoid them in publicly available websites. So assuming you need this for only one controller and route this option is the fastest and cleanest one.

like image 135
Piotr Leniartek Avatar answered Dec 31 '22 01:12

Piotr Leniartek