在global.asax中执行具有区域和依赖注入的控制器

时间:2014-03-04 22:08:30

标签: c# asp.net-mvc asp.net-mvc-3 global-asax

我正在尝试从global.asax执行控制器。控制器位于根控制器文件夹中,但错误发生在Web应用程序内的区域内的控制器中。以下是global.asax代码:

protected override void Application_Error(object sender, EventArgs e)
{
    var routeData = new RouteData();
    routeData.Values["controller"] = "error";
    routeData.Values["exception"] = ex;
    routeData.Values["action"] = "Index";
    routeData.Values["ErrorCode"] = 503;

    IController controller = ControllerBuilder.Current.GetControllerFactory().CreateController(HttpContext.Current.Request.RequestContext, "Error");
    controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
}

这是我得到的错误:

The controller for path '/1985-books/usa/3rhvasdfasfd' was not found or does not implement IController.

更新

当控制器不在area时,此代码工作正常,一旦我在错误发生的控制器的情况下使用此代码,就会发生此错误。我有一种感觉,默认情况下,它正在查找根目录中的Error,一旦它变得有点复杂Error写在uest.RequestContext, "Error");中找不到正确的路径。

1 个答案:

答案 0 :(得分:3)

我认为您需要首先添加对Server.ClearError的调用,以便它知道您是以自定义方式处理错误:

    protected void Application_Error(object sender, EventArgs e)
    {
        // capture the exception beforehand  if you need to
        var exception = Server.GetLastError();
        // Tell the server we're handling the error "our way"
        Server.ClearError();
        ...
        // You may also need to reset the response type
        Context.Response.ContentType = "text/html";
        controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
    }

更新

尝试使用您创建的RequestContext时,首先尝试构建控制器:

var requestContext = new RequestContext(
    new HttpContextWrapper(Context), routeData);
IController controller = ControllerBuilder.Current.GetControllerFactory()
    .CreateController(requestContext, "Error");
controller.Execute(requestContext);