在MVC站点上,你可以优先使用IIS中的Url重写模块来覆盖MVC路由吗?
本文关键字:MVC 模块 重写 中的 Url 覆盖 路由 IIS 站点 | 更新日期: 2023-09-27 17:50:14
我有一个MVC网站,其中有路由,我需要与IIS Url重写模块重定向,因为我不能重建网站(不要问)。所以我想我可以使用IIS Url重写器并输入一些网页。配置值以执行重定向。问题是MVC路由首先得到处理,所以url重写模块永远不会被击中。
是否有办法使Url重写的第一个处理程序,然后回落到MVC路由?
我的环境是MVC2 c# Asp. NET 3.5 on IIS 7.5 Win Server 2008 R2
谢谢你的帮助
好的,所以我发现我不能这样做,而不创建一个HttpModule。这真的很简单,通过使用IHttpModule创建模块的代码,然后在web配置中注册为:
public class HttpRedirectModule: IHttpModule
{
public HttpRedirectModule()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(ContextBeginRequest);
}
void ContextBeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
if (application.Application["Redirects"] == null)
{
var repository = Factory.GetInstance<IRepository>();
application.Application["Redirects"] = repository.GetAll<Redirect>();
}
var redirects = (IList<Redirect>) application.Application["Redirects"];
if (application.Request.Url.AbsolutePath != "/default.aspx")
{
foreach (var redirect in redirects)
{
var regex = new Regex(redirect.FromPath);
Match match = regex.Match(application.Request.Url.AbsolutePath);
if (match.Success)
{
application.Response.Clear();
if (redirect.StatusCode == 301)
{
application.Response.Status = "301 Moved Permanently";
application.Response.StatusCode = 301;
}
else
{
application.Response.Status = "302 Moved temporarily";
application.Response.StatusCode = 302;
}
application.Response.AddHeader("Location", redirect.ToPath);
application.Response.End();
}
}
}
}
public void Dispose()
{
}
}
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="RedirectsModule" />
<add name="RedirectsModule" type="MyCode.HttpModules.HttpRedirectModule, MyCode" />
</modules>
</system.webServer>
您可以在全局代码中添加任何代码。