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

后端 未结 2 1499
梦谈多话
梦谈多话 2021-02-10 09:13

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

相关标签:
2条回答
  • 2021-02-10 09:45

    We had this same issue (albeit not with attribute routing) and it started to appear in MVC 4 and continues in every version since.

    One of the contributors to our project discovered the solution. I am afraid I can't offer much of an explanation as to why, but removing and then replacing the UrlRoutingModule fixes the 404 problem when using a route with a . in it.

    <configuration>
        <system.webServer>
            <modules>
                <remove name="UrlRoutingModule-4.0" />
                <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />
            </modules>
        </system.webServer>
    </configuration>
    

    This was discovered about 2 years ago, and so far we have not run into any negative effects caused by this change.

    BTW - If anyone has an explanation why this works, please do share.

    0 讨论(0)
  • 2021-02-10 09:55

    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.

    0 讨论(0)
提交回复
热议问题