从 MVC 应用中的 OnException 方法路由到视图



当操作中抛出异常时,我正在尝试将应用程序重新路由到同一视图:

[HttpPost]
public EmptyResult Action(ModelClass modelObject)
{
    _facade.update(modelObject);
    return new EmptyResult();
}

protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.Exception is MyException)
    {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/ViewFolder/View.cshtml",
            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
            TempData = filterContext.Controller.TempData
        };

        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
    base.OnException(filterContext);
}

我错过了什么?

视图名称按约定映射。您无需放置完整路径。

结果的视图名称

将具有显式的视图名称 传入结果。在运行时,如果未指定视图名称 则 ASP.NET MVC 将使用由 路由系统。它没有办法在单元测试中"猜测" 视图名称应该是什么。

您可以在 StackOverflow.com 上找到有关此帖子的更多信息: 对控制器方法进行单元测试会导致视图名称为空?

protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.Exception is MyException)
    {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
        filterContext.Result = new ViewResult
        {
            ViewName = actionName,
            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
            TempData = filterContext.Controller.TempData
        };    
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
    base.OnException(filterContext);
}

最新更新