ASP.NET MVC Url中带点号出现404错误的解决方案

由于项目需求,项目的路由设计如下

  config.Routes.MapHttpRoute(
                name: "Get/Put Sku",
                routeTemplate: "apiSets/{apiSetName}",
                defaults: new { controller = "Sku" },
                constraints: new { httpmethod = new HttpMethodConstraint(HttpMethod.Get, HttpMethod.Put) },
                handler: authHandler
            );
  config.Routes.MapHttpRoute(
                name: "Validate Sku",
                routeTemplate: "apiSets/{apiSetName}/validate",
                defaults: new { controller = "Sku" },
                constraints: new { httpmethod = new HttpMethodConstraint(HttpMethod.Post) },
                handler: authHandler
            );

该路由设计会出现如下问题:

  当Url中{apiSetName}对应位置出现点(.)的时候,Url将找不到可以匹配的路由,比如Url: ../apiSets/Bing.Search 将无法找到匹配的路由而报出404错误,参照http://stackoverflow.com/questions/11728846/dots-in-url-causes-404-with-asp-net-mvc-and-iis中网友的说法,在一般情况下,当在Url中最后的一块中出现点号(.)时,MVC将把它当做一个文件来处理,去查找相应的文件,找不到对应的文件就报404错误了。

但是Url: ../apiSets/Bing.Search/validate 可以正确的匹配路由,是因为点号(.)出现在Url的中间位置,不是最后一块,MVC不会将其作为文件处理。

现有两种方式可以解决这个问题:

1、在项目的web.config文件中做如下设置:

  在<system.webServer></system.webServer>节点中添加如下代码:

    <modules runAllManagedModulesForAllRequests="true"></modules>

这种方式是不推荐的,在 (1)http://bartwullems.blogspot.jp/2012/06/optimize-performance-of-your-web.html 和(2)http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html中都有提及。因为将runAllManagedModulesForAllRequests设置为true之后,将会使所有已注册的HTTP模块在每个请求上运行,而不仅仅是托管请求(例如.aspx)。 这意味着模块将运行在.jpg .gif .css .html .pdf等。这将导致资源的浪费,并且会引发其他的Error。

(推荐)2、在web.config中配置如下:

  在<system.webServer></system.webServer>节点中添加如下代码:

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

    

参考网址:

1.http://www.hanselman.com/blog/BackToBasicsDynamicImageGenerationASPNETControllersRoutingIHttpHandlersAndRunAllManagedModulesForAllRequests.aspx 

2.http://stackoverflow.com/questions/16581184/mvc4-404-errors

原文地址:https://www.cnblogs.com/Herzog3/p/6274676.html