一个在 IIS7 中不起作用的 HttpModule
我有一个 HttpModule,可以重定向 ASP.NET WebForms 应用程序中的某些 URL。它可以在我的机器上运行 ASP.NET 开发服务器。但是当我用IIS7上传到我们的Win2k8服务器时,它似乎根本没有反应。我已将
放在 system.webServer/modules 部分中,并且在 inetmgr 中我可以在其他模块中看到该模块。在我上传代码之前和之后,该网站的行为似乎相同,但事实并非如此。
编辑后的代码示例:
public void Init(HttpApplication context)
{
context.Error += PageNotFoundHandler;
}
public static void PageNotFoundHandler(object sender, EventArgs evt)
{
Exception lastErrorFromServer = HttpContext.Current.Server.GetLastError();
if (lastErrorFromServer != null)
{
RedirectToNewUrlIfApplicable();
}
}
private static void RedirectToNewUrlIfApplicable()
{
string redirectUrl = GetRedirectUrl();
if (!string.IsNullOrEmpty(redirectUrl))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", redirectUrl);
}
}
private static string GetRedirectUrl()
{
return RedirectableUrls.GetUrl();
}
I have a HttpModule that redirects certain URL:s in an ASP.NET WebForms application. It works on my machine with the ASP.NET Development Server. But when I upload it to our Win2k8 server with IIS7, it doesn't seem to react at all. I've put the <add name="Test.Web" type="Test.Web.Core.HttpModules.RedirectOldUrls, Test.Web" />
in the system.webServer/modules section, and in inetmgr I can see the module amongst the other ones. The website seems to behave the same way before and after I upload the code, which it shouldn't.
An edited code example:
public void Init(HttpApplication context)
{
context.Error += PageNotFoundHandler;
}
public static void PageNotFoundHandler(object sender, EventArgs evt)
{
Exception lastErrorFromServer = HttpContext.Current.Server.GetLastError();
if (lastErrorFromServer != null)
{
RedirectToNewUrlIfApplicable();
}
}
private static void RedirectToNewUrlIfApplicable()
{
string redirectUrl = GetRedirectUrl();
if (!string.IsNullOrEmpty(redirectUrl))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", redirectUrl);
}
}
private static string GetRedirectUrl()
{
return RedirectableUrls.GetUrl();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许我错过了一些东西。但是您是否在
system.webServer
部分中定义了HttpModule
?另外,您是否将 runAllManagedModulesForAllRequests 设置为 true?Maybe I'm missing something. But did you define your
HttpModule
in thesystem.webServer
section? And also, did you set therunAllManagedModulesForAllRequests
to true?显然,IIS7 不接受使用 HttpContext.Error,如下所示:
相反,我必须这样做:
这似乎有效。为什么,我不知道。我只想在 404 错误出现在用户面前之前将重定向作为最后的手段。
Apparently, the IIS7 did not accept using HttpContext.Error, like this:
Instead, I had to do like this:
Which seems to work. Why, I don't know. I only wanted to redirect as a last resort before a 404 is dumped in the face of the user.