在 MVC4 中路由带有扩展名的 url 将不起作用,尝试提供静态文件 [英] Routing a url with extension in MVC4 won't work, tries to serve up static file
问题描述
我正在使用 MVC4,需要将这样的请求路由到控制器:
I'm using MVC4 and need to route a request like this to a controller:
[myapp]/data/fileinfo.xml
这是我配置的路由:
routes.MapRoute(
name: "Data",
url: "Data/{file}",
defaults: new { controller = "Data", action = "fileinfo"}
);
现在,如果 URL 不包含 .xml 扩展名,这可以正常工作并将请求路由到我的 DataController,但是一旦使用扩展名,IIS 就会尝试提供静态文件(而不是路由到我的控制器)并且我收到 404 错误.
Now, this works perfectly fine and routes requests to my DataController if the URL does not include the .xml extension, but as soon as an extension is used, IIS tries to serve up a static file (instead of routing to my controller) and I get a 404 error.
我在网上阅读了大量有关此问题的问题/答案,但我尝试过的每个解决方案都失败了.
I've read loads of questions/answers about this issue online, and every solution I've tried has failed.
例如,我在配置我的 RouteCollection 时尝试使用 RouteExistingFiles = true
,并且我添加了 <modules runAllManagedModulesForAllRequests="true"/>
web.config,但无济于事.
For example, I've tried using RouteExistingFiles = true
when configuring my RouteCollection, and I've added <modules runAllManagedModulesForAllRequests="true" />
in web.config, but to no avail.
如果有人知道我应该尝试什么或我可能会遗漏什么,我们将不胜感激.我使用的是 asp.Net 4.5、VS 2012 和 IIS 8.0.
If anyone has an idea of what I should try or what I may be missing, it would be much appreciated. I'm using asp.Net 4.5, VS 2012 and IIS 8.0.
推荐答案
您可以在 <system.webServer><handlers>
部分将其添加到您的 web.config 中:
You can add this to your web.config in the <system.webServer><handlers>
section:
<add name="ManagedDllExtension"
path="data/fileinfo.xml"
verb="GET" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
你的路线是
routes.MapRoute(
name: "Data",
url: "Data/fileinfo.xml",
defaults: new { controller = "Data", action = "fileinfo"}
);
还有 <modules runAllManagedModulesForAllRequests="true">
但它似乎不适用于 MVC4/IIS8(过去在 MVC3/IIS7 IIRC 中没问题).更多信息此处.这也会对性能产生影响,因为每个请求都将通过托管管道进行路由.
There is also <modules runAllManagedModulesForAllRequests="true">
but it doesn't seem to work for MVC4/IIS8 (used to be ok in MVC3/IIS7 IIRC). More info here. There is also a performance impact with this one as every request will route through the managed pipeline.
HTH
这篇关于在 MVC4 中路由带有扩展名的 url 将不起作用,尝试提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!