MVC路由静态化
mvc 标准的写法 通常是(http://localhost:8149/Home/Index) 路由配置如下:
有时候需求 如 http://localhost:8149/Home/Index 改为http://localhost:8149/index.html 让其看起来更加像一个静态网站
1
2
|
//配置首页 伪静态 路由 routes.MapRoute( "pc_index" , "index.html" , new { controller = "Home" , action = "Index" }); |
然而
解决方式一(不建议)修改 Web.config 文件
1
2
3
4
|
<system.webServer> <modules runAllManagedModulesForAllRequests= "true" > </modules> </system.webServer> |
这种方式强烈不建议:
1、这些问题的形式是使所有注册的HTTP模块在每个请求上运行,而不仅仅是托管请求(例如.html)。 这意味着模块将永远运行.jpg .gif .css .aspx等
2、浪费资源
3、并具有可能导致错误的全局效应
更好的解决方案(方式二)
1
2
3
4
5
6
|
<system.webServer> <modules > <remove name= "UrlRoutingModule-4.0" /> <add name= "UrlRoutingModule-4.0" type= "System.Web.Routing.UrlRoutingModule" preCondition= "" /> </modules> </system.webServer> |
更好的解决方案(方式三)
1
2
3
4
5
|
<system.webServer> <handlers> <add name= "htmlHandler" verb= "GET,HEAD" path= "*.html" type= "System.Web.StaticFileHandler" /> </handlers> </system.webServer> |
mvc有专门获取路由参数的方式,在不同的地方,获取路由参数的方式也不一样,这里分别说一下,在controller,非controller的类里面,和view里如何获取路由参数:
1.在controller里获取路由参数:
1
|
var controller = RouteData.Values[ "controller" ]; //action,id或其他路由参数同理 |
2.在view中获取:
1
|
<input type= "text" value= "@Html.ViewContext.RouteData.Values[" controller "]" /> |
3.在非controller的类中:
1
|
HttpContext.Current.Request.RequestContext.RouteData.Values[ "controller" ] |
作者:Artech
出处:http://artech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。