【问题标题】:Render error view when we encounter an exception遇到异常时渲染错误视图
【发布时间】:2013-08-08 12:28:21
【问题描述】:

我怎样才能以另一种方式做到这一点?

public ActionResult SomeAction(int id)
{
    try
    {            
        var model = GetMyModel(id);
        return View(model);
    }
    catch(Exception e)
    {
        var notFoundViewModel = new NotFoundViewModel { Some Properties };
        return View("~/Views/Shared/NotFound.cshtml", notFoundViewModel);
    }
}

url Controller/SomeAction/NotFoundId 将抛出异常。我讨厌在项目中有这样的东西:~/Views/Shared/NotFound.cshtml

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

我意识到这个问题已经有几年的历史了,但我想我会添加到已接受的答案中。按照 CodeCaster 建议使用标准的“Error.cshtml”作为文件(视图)来充当您的通用错误页面,我建议您让 MVC 框架为您完成剩下的工作。

如果将 Error.cshtml 文件放在 MVC 项目的 Shared 文件夹中,则无需显式指定视图的路径。你可以像下面这样重写你的代码:

public ActionResult SomeAction(int id)
{
    try
    {            
        var model = getMyModel(id);
        return View(model);
    }
    catch(Exception e)
    {
        var NotFoundViewModel = new NotFoundViewModel { Some Properties };
        return View("Error", NotFoundViewModel);
    }
}

事实上,我注意到如果您提供显式路径并在本地计算机上运行 Visual Studio IIS Express,它有时无法找到该文件并显示通用 404 消息:(

【讨论】:

    【解决方案2】:

    您可以将 HttpNotFoundResult 对象返回为:

    catch(Exception e)
    {
        return new HttpNotFoundResult();
    }
    

    catch(Exception e)
    {
        return HttpNotFound("ooops, there is no page like this :/");
    }
    

    【讨论】:

      【解决方案3】:

      将其设为"~/Views/Shared/Error.cshtml",显示带有标题和消息的通用错误模型?

      【讨论】:

      • 这看起来不错。我必须有一个错误控制器,这样我才能将 RedirectToAction 与 NotFoundAction 和我的 NotFoundViewModel 作为参数返回。在 NotFoundAction 中,我将渲染我的 NotFoundView 。可以吗?
      • 或者看看this question