我如何执行从ASP.NET MVC的HTTP模块控制器的动作? [英] How do I execute a controller action from an HttpModule in ASP.NET MVC?

查看:117
本文介绍了我如何执行从ASP.NET MVC的HTTP模块控制器的动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 IHttpModule的,我试图找出如何从一个控制器,一个给定的绝对或相对URL执行操作。

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?

推荐答案

东西沿线应该做的工作:

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);
}

您可能会发现下面的<一个href="http://stackoverflow.com/questions/5226791/custom-error-pages-on-asp-net-mvc3/5229581#5229581">related回答有用的。

You might also find the following related answer useful.

这篇关于我如何执行从ASP.NET MVC的HTTP模块控制器的动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆