我有一个奇怪的问题。我正在处理一些设置为无扩展名运行的 MVC 代码,如 /Home/Index?id=10
但是,它曾经是为 IIS 6 设置的,并且使用的是 .mvc 扩展名在所有 Controller 上,如 /Home.mvc/Index?id=10
中所示。
我希望这两条路线都能工作。在我的 global.asax.cs 文件中,我创建了以下代码:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("Default2",
"{controller}.mvc/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
这几乎成功了!但不幸的是,当我的 Controller 返回 RedirectToAction 时,生成的 URL 失败。
我这样调用 RedirectToAction:
return RedirectToAction("Index", "Account");
它返回这个:
/Account.mvc
现在假定索引,所以我不担心它丢失了。但是,该 URL 的末尾没有 /
,因此返回 404 错误。如果我添加 /
它工作正常。有什么方法可以帮助 MVC 正确生成 URL,或者有什么方法可以修改路由以使其识别此 URL?
背景:我遇到这种情况是因为在将网络服务器升级到 IIS 7.5 后,我开始将我的应用程序转换为使用无扩展 URL。我没有意识到与外界共享的应用程序中有很多链接——更改为无扩展会破坏所有这些链接。呸!应该一个人呆着就好了。
最佳答案
我个人会使用 URL Rewriter .你可以Redirect ASP.NET Legacy URLs to Extensionless with the IIS Rewrite Module .
例如,您可以创建一个看起来像(不完全是,它们确实需要测试)的出站规则:
<outboundRules>
<rule name="remove .mvc outbound 1">
<match serverVariable="RESPONSE_LOCATION"
pattern="^/(.*).mvc$" />
<action type="Rewrite" value="/{R:1}" />
</rule>
<rule name="remove .mvc outbound 2">
<match filterByTags="A, Form, IFrame, Img, Input, Link, Script"
pattern="^/(.*).mvc$" />
<action type="Rewrite" value="/{R:1}" />
</rule>
</outboundRules>
如果有人决定对 MVC 扩展进行硬编码......
<rule name="Add Slash Inbound">
<match url="(.*)" />
<conditions>
<add input="{PATH_INFO}" pattern="^/(.*).mvc$" negate="true" />
</conditions>
<action type="Rewrite" url="{R:0}/" />
</rule>
关于asp.net-mvc - .mvc 和无扩展名 URL 的 MVC 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663115/