asp.net mvc 之路:静态与伪静态页面的切换

来源:互联网 发布:好未来php面试题 编辑:程序博客网 时间:2024/04/30 04:59

本文针对asp.net中mvc下routes添加自定义路由实现伪静态
切换的实质就是实现了当系统中静态页面尚未生成时,外部访问已公布的地址时能返回动态页面;当静态页面已经生成之后,访问就是直接对静态页面的访问。

一 、添加自定义的routes路由

    public class RouteConfig    {        public static void RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            //name=article的路由是我自定义的的路由            routes.MapRoute(                 name: "Article",                 url: "{controller}/{id}/{htmlname}.html",                 defaults: new { action = "Index", id = UrlParameter.Optional, htmlname = UrlParameter.Optional },                 constraints: new { action = "Index" }                 );            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }            );        }    }    

二、webconfig中增加对后缀.html交由asp.net处理的映射
在webconfig的

      <add name="RewriteHtml64" path="*.html" verb="*" type="System.Web.Handlers.TransferRequestHandler" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="bitness64" />      <add name="RewriteHtml32" path="*.html" verb="*" type="System.Web.Handlers.TransferRequestHandler" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="bitness32" />

这里我是对64位系统和32位系统都做了映射,我使用的是net4.5。
至此
伪静态功能已经实现了。
伪静态测试图片
三、实现静态页面与动态页面直接的切换
我是在global中Application_BeginRequest里面进行处理

        protected void Application_BeginRequest()        {            HttpContext context = HttpContext.Current;            string requestHtmlPath = context.Request.Path;            //如果请求中带有html的后缀,需要进行处理            if (requestHtmlPath.EndsWith(".html"))            {                string serverPath = context.Server.MapPath(requestHtmlPath);                if (File.Exists(serverPath))                //直接重写地址,不会产生跳转请求                    context.RewritePath("~" + requestHtmlPath);            }        }

这里会产生一个问题,就是如果是伪静态的页面,能正常访问,但是重写地址之后,访问真正的静态页面,就会出现“未能执行 URL。”错误。这时只需要在webconfig的system.web节点下添加

    <httpHandlers>      <add  verb="*" path="*.html" type="System.Web.StaticFileHandler" />    </httpHandlers>

就能正常访问静态页面了。
*现在还有个问题就是,如果调试时使用vs自带的iisexpress,在访问静态页面时,会出现服务程序不可用的错误。如果哪位知道原因,还请留言告诉我怎么解决。*
这只是我自己琢磨出来的方法,请大家留言指点,或者提供其它更好的解决方案。

原创粉丝点击