如何为(现已不存在)index.html(也就是穷人的URL重写)触发global.asax?

时间:2015-04-13 21:36:17

标签: c# asp.net url-rewriting global-asax

我需要用 index.cshtml 透明地替换 index.html 。问题是我无法将更改推送给客户 - 他们将继续使用 index.html

接下来,我们的IIS没有IIS URL Rewrite Extension,我不能指望它能够实现。

基本上,我需要自己实现重写。但是,当请求 index.html 时,我的global.asax未被触发,这是有道理的。

所以,我的问题是如何为 index.html 触发global.asax

现在,我确实得到了一个答案,但是由于我不是ASP.NET开发人员,因此可能是一个糟糕的答案。

我很乐意接受有关如何使用不同,更有效和/或更简单的方法重写URL的答案。但是,没有HTTP重定向。

P.S。

该应用程序不包含路由,没有控制器和视图。它本质上是一个静态站点(html + javascript)。 cshtml的唯一原因是必须在服务器端的运行时计算某些资源路径。

1 个答案:

答案 0 :(得分:0)

我的解决方案对我来说已经足够了。基本上,它是index.html URL的重写。

回顾一下: 首先,我在web.config中为index.html引入了一个虚处理程序:

<system.webServer>
  <handlers>
    <!-- The handler name is not an error !!! -->
    <add name="IndexHtmlHandler" verb="GET" path="index.html" type="Bogus.NonExisting.VirtualHandler" />
  </handlers>
</system.webServer>

这足以触发global.asax,它处理实际的重写:

void Application_BeginRequest(object sender, EventArgs e)
{
    var context = HttpContext.Current;
    if (context.Request.Path.EndsWith("index.html"))
    {
        context.RewritePath(context.Request.Path.Replace(".html", ".cshtml"));
    }
}