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

我只是一个虾纸丫 提交于 2019-12-30 05:27:15

问题


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?


回答1:


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.




回答2:


I think you need to use HttpContext.Current.RewritePath

This lets you change the path for the file you want to use. It's what the default.aspx created in MVC 2 projects does.

I've used it in much the same way you are, to do error handling without a 302 but can't get to my code right now. I'll post some code on Monday.




回答3:


You can using HttpContext:

System.Web.HttpContext.Current.Response.Redirect("/Error/NotFound");



回答4:


Hi use this to let the framework execute the code for that path using the routing and all the components :

    // MVC 3 running on IIS 7+
    if (HttpRuntime.UsingIntegratedPipeline)
    {
        context.Server.TransferRequest(url, true);
    }
    else
    {
        // Pre MVC 3
        context.RewritePath(url, false);

        IHttpHandler httpHandler = new MvcHttpHandler();
        httpHandler.ProcessRequest(httpContext);
    }

And ideally the request processing is completer at this point. If this is not the case and if the request is further processed along the asp.net http pipeline, then use this to stop the request at this point, and tell asp.net that we're done with this request :

HttpApplication app = (HttpApplication) context.Application;
app.CompleteRequest();;

Im not sure if the context has the Application (im not near VS now) but use it to stop the request in this module if needed.



来源:https://stackoverflow.com/questions/6972521/how-do-i-execute-a-controller-action-from-an-httpmodule-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!