问题描述
|
我有一个MVC站点,该站点的路由需要使用IIS Url ReWrite模块进行重定向,因为我无法重建该站点(不要问)。所以我想我可以使用IIS Url ReWriter并输入一些web.config值来执行重定向。问题是首先要处理MVC路由,因此永远不会点击url重写器模块。
有没有办法让Url ReWriter成为第一个处理程序,然后回退到MVC路由?
我的环境是IIS 7.5 Win Server 2008 R2上的MVC2 c#Asp.NET 3.5
谢谢你的帮助。
解决方法
好的,所以我发现如果不创建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>
,您可以在添加URL路由之前将任何代码添加到global.asax中。