前一阵子用MVC做了个网站项目要求以静态html格式来访问,说是这样对搜索引擎更加友好,今天我就将解决方法分享给大家。
一共可以通过三个步骤来实现。
一 、添加自定义的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" } ); } }
二、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>
就能正常访问静态页面了。
通过以上内容我们知道了MVC/C#如何以静态html格式访问,感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!