Search code examples
c#.netasp.net-mvchttpmodule

How do I execute a controller action from an HttpModule in ASP.NET MVC?


I've got the following IHttpModule and I'm trying to figure out how to execute an action from a controller for a given absolute or relative URL.

public class CustomErrorHandlingModule : IHttpModule
{
    #region Implementation of IHttpModule

    public void Init(HttpApplication context)
    {
        context.Error += (sender, e) => 
            OnError(new HttpContextWrapper(((HttpApplication)sender).Context));
    }

    public void Dispose()
    {}

    public void OnError(HttpContextBase context)
    {
        // Determine error resource to display, based on HttpStatus code, etc.
        // For brevity, i'll hardcode it for this SO question.
        const string errorPage = @"/Error/NotFound";

        // Now somehow execute the correct controller for that route.
        // Return the html response.
    }
}

How can this be done?


Solution

  • Something along the lines should do the job:

    public void OnError(HttpContextBase context)
    {
        context.ClearError();
        context.Response.StatusCode = 404;
    
        var rd = new RouteData();
        rd.Values["controller"] = "error";
        rd.Values["action"] = "notfound";
        IController controller = new ErrorController();
        var rc = new RequestContext(context, rd);
        controller.Execute(rc);
    }
    

    You might also find the following related answer useful.