[英]Executing a controller in global.asax which has area and dependency injection
我試圖從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");
找不到正確的路線。
我認為您需要首先添加對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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.