遇到异常时渲染错误视图

时间:2013-08-07 08:15:33

标签: c# asp.net-mvc

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

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);
    }
}

将为网址Controller/SomeAction/NotFoundId抛出异常。我不喜欢在项目中使用:~/Views/Shared/NotFound.cshtml

3 个答案:

答案 0 :(得分:4)

我意识到这个问题已经有几年了,但我想我会加入已接受的答案。遵循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消息:(

答案 1 :(得分:2)

您可以将HttpNotFoundResult对象返回为:

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

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

答案 2 :(得分:1)

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