C#mvc4 ViewResult如何设置控制器和区域?

时间:2014-10-30 16:02:09

标签: c# asp.net-mvc-4

public override void OnException(ExceptionContext filterContext) {

    string controllerName = (string) filterContext.RouteData.Values["controller"];
    string actionName = (string) filterContext.RouteData.Values["action"];
    // Preserve old ViewData here
    var viewData = new ViewDataDictionary<HandleErrorInfo>(filterContext.Controller.ViewData); 
    // Set the Exception information model here
    viewData.Model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
    filterContext.Result = new ViewResult { ViewName = this.View, MasterName = this.Master, ViewData = viewData, TempData = filterContext.Controller.TempData };
    filterContext.ExceptionHandled = true;
    filterContext.HttpContext.Response.Clear();
    //filterContext.HttpContext.Response.StatusCode = 500;
    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

但我得到错误:

{System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched:
xxxxxxxx

但我的位置不是搜索。 Error方法在MyErrorController中。如何显式设置控制器(MyErrorController

我的路径必须是〜/ Areas / Public / Views / MyError / Error.ascx

"area" -> "Public"
"controller", "MyError"
"action" -> "Error";

1 个答案:

答案 0 :(得分:4)

在设置filterContext.Result之前,请尝试添加以下行:

filterContext.RouteData.DataTokens["area"] = "Public";
filterContext.RouteData.Values["controller"] = "MyError";
filterContext.RouteData.Values["action"] = "Error";