首页 > 技术文章 > ASP.NET MVC 5 伪静态之支持*.html路由

zhuji 2019-09-10 16:02 原文

参考了例子 到自己实践还是有不少坑要踩,这种文章,你说它好还是不好呢

注意这里的版本是ASP.NET MVC 5

首页的URL为  http://localhost:58321/index.html  或   http://localhost:58321/

第一步是让 ASP.NET MVC 5 支持 html后缀的请求, 到ASP.NET MVC 5 项目根目录的的Web.config在增加配置

  <system.webServer>
    <handlers>
      <add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>

应该有2种方式,只实践出一种,有2处改动,一.Global.asax.cs增加处理方法, 二.在RouteConfig.cs增加对index.html的路由
在Global.asax.cs中增加

protected void Application_BeginRequest()
{
    HttpContext context = HttpContext.Current;
    string requestHtmlPath = context.Request.Path;
    //如果请求中带有html的后缀,需要进行处理
    if (requestHtmlPath.EndsWith("index.html"))
    {
        context.RewritePath("~");
    }
}

在RouteConfig.cs

routes.MapRoute(
    name: "HomePage",
    url: "index.html",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "CBBC.XXX.Controllers" }
)

 

尝试了 ASP.NET MVC5 新特性:Attribute路由

配了之后 http://localhost:58321/index.html 可以跳转到 HomeController的Index方法 但 http://localhost:58321/ 无法找到页面

[HttpGet]
[Route("index.html")]
public ActionResult Index()
{
    return View();
}

发现http://localhost:58321/ 无法找到页面,暂时未找到解决方案.

 

推荐阅读