如何从ASP.NET MVC中的HttpModule执行控制器操作?

Pur*_*ome 1 .net c# asp.net-mvc httpmodule

我有以下内容IHttpModule,我正在试图弄清楚如何从控制器为给定的绝对或相对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.
    }
}
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

Dar*_*rov 7

沿线的东西应该做的工作:

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);
}
Run Code Online (Sandbox Code Playgroud)

您可能还会发现以下相关答案很有用.