I tried to do redirect from w/i httpmodule. I have the following code in place, and hooked up in the httpModules section. This Error event is fired as expected, but this didn't go to the /Error/Index page.
public class MyHttp开发者_JAVA技巧Module : IHttpModule {
public void Dispose() { }
public void Init(HttpApplication context) {
context.Error += delegate {
var exception = context.Server.GetLastError();
context.Response.Clear();
context.Response.TrySkipIisCustomErrors = true;
context.Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData));
};
}
}
Please advice, Thanks
I created a new ASP.NET MVC 2 and ASP.NET MVC 3 application.
I added a new HttpModule and copy/pasted your code.
I registered the new HttpModule in the Web.config.
<?xml version="1.0"?>
<configuration>
<system.web>
<httpModules>
<add name="MyHttpModule"
type="MvcApplication.MyHttpModule, MvcApplication" />
</httpModules>
</system.web>
</configuration>
I throw an exception in one of the action methods of my controller, e.g.:
throw new InvalidOperationException("An exception occured.");
Whenever an unhandled exception occurs I get redirected to the Error/Index page without a problem.
Have you correctly registered the HttpModule? I only get the described behavior if the module is not registered correctly. Keep in mind that for the Visual Studio Development Web Server (Cassini) and IIS 7.X you need to register the HttpModule in different sections of the Web.config.
For IIS 7.X please use:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<modules>
<add name="MyHttpModule"
type="MvcApplication.MyHttpModule, MvcApplication" />
</modules>
</system.webServer>
</configuration>
精彩评论