关于.NET MVC的伪静态实现,网上有很多博文介绍,但都不能实现真正的伪静态,或者适应更复杂的伪静态需求,比如分页查询的页面。
首先,我们要写一个路由拦截器,其中的一些拦截规则处理,需要你根据实际情况处理,我这里只是扩展了分页查询的伪静态处理,代码如下:
/// <summary> /// 路由拦截器 /// 作者:Maximus Ye /// Email:yq@yyzq.net /// QQ:275623749 /// </summary> public class MVCHtmlRoute : RouteBase { public MVCHtmlRoute() { } public override RouteData GetRouteData(HttpContextBase httpContext) { RouteData result = null; string requestedURL = httpContext.Request.AppRelativeCurrentExecutionFilePath + httpContext.Request.PathInfo; List<string> URLItemList = requestedURL.Split('/').ToList(); if(URLItemList.Count()==3) {//缺Action int extpos = URLItemList[2].IndexOf(".html"); int pagepos = URLItemList[2].IndexOf("_"); if (extpos > 0) { result = new RouteData(this, new MvcRouteHandler()); result.Values.Add("controller", URLItemList[1]); result.Values.Add("action", "Index"); if (pagepos > 0) {//分页参数分割 result.Values.Add("id", URLItemList[2].Substring(0, pagepos)); result.Values.Add("page", URLItemList[2].Substring(pagepos + 1, extpos - pagepos-1)); } else { result.Values.Add("id", URLItemList[2].Substring(0, extpos)); } } } return result; } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return null; } }然后在Global.asax的RegisterRoutes方法中添加我们的拦截器,并添加其他伪静态规则,代码如下:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add(new Lib.MVCHtmlRoute()); routes.MapRoute( "ID_PAGEHtml", // id伪静态 扩展分页参数page "{controller}/{action}/{id}_{page}.html",// 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional, page = UrlParameter.Optional }// 参数默认值 ); routes.MapRoute( "IDHtml", // id伪静态 "{controller}/{action}/{id}.html",// 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional }// 参数默认值 ); routes.MapRoute( "ActionHtml", // action伪静态 "{controller}/{action}.html/{id}",// 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional }// 参数默认值 ); routes.MapRoute( "ControllerHtml", // controller伪静态 "{controller}.html/{action}/{id}",// 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional }// 参数默认值 ); //以下保证未做伪静态处理的链接也能正常识别 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }// 参数默认值 ); routes.MapRoute( "Root", "", new { controller = "Home", action = "Index", id = UrlParameter.Optional });//根目录匹配 }好了,以上要弄的都弄好了,具体的伪静态效果,可以访问:www.etagrfid.com查看。
转载请注明出处,谢谢!
原文地址:http://blog.csdn.net/sqqyq/article/details/39077397