mvc实现伪静态
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mvc实现伪静态相关的知识,希望对你有一定的参考价值。
也不知道我写的算不算的伪静态,反正是可以更改URL的后缀名(新手,见谅)
实现这个也是在网上找的,地址:http://www.jb51.net/article/29198.htm
首先添加一个TestRoute类
public class TestRoute:RouteBase { private string[] urls; public TestRoute(params string[] targetUrls) { urls = targetUrls; } public override RouteData GetRouteData(HttpContextBase httpContext) { RouteData result = null; string requestedURL = httpContext.Request.AppRelativeCurrentExecutionFilePath + httpContext.Request.PathInfo; requestedURL = requestedURL.Substring(2).Trim(‘/‘); if (requestedURL.Contains(urls.ToArray().GetValue(0).ToString())) { result = new RouteData(this, new MvcRouteHandler()); result.Values.Add("controller", "Home"); result.Values.Add("action", "Index"); result.Values.Add("p", requestedURL); } return result; } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { if (values["controller"].ToString().Contains("Home")) { return new VirtualPathData(this, "Home/" + values["p"] + ".html"); } else return null; } }
然后在我们的Global文件里定义我们自己的路由规则
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); // RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add(new TestRoute("User")); routes.Add(new TestRoute("Home")); routes.Add(new TestRoute("JieKuan")); routes.Add(new TestRoute("Loan")); routes.Add(new TestRoute("Admin")); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters // new { controller = "Test", action = "Index", id = UrlParameter.Optional }, // Parameter defaults new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
最后在Web.Config配置文件里<system.WebServer>下的<handlers>标签下加入以下代码
<add name="hh" verb="GET,HEAD" path="*.html" type="System.Web.StaticFileHandler"/> <add name="hhh" path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
实现了以上步骤我们便可以更改我么的URL地址的后缀名了。
写的不好,欢迎大家指正。
以上是关于mvc实现伪静态的主要内容,如果未能解决你的问题,请参考以下文章