4

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

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.

4

3 回答 3

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 消息:(

于 2015-09-16T20:53:22.480 回答
2

您可以将 HttpNotFoundResult 对象返回为:

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

或者

catch(Exception e)
{
    return HttpNotFound("ooops, there is no page like this :/");
}
于 2013-08-07T08:27:14.737 回答
1

Make it a "~/Views/Shared/Error.cshtml" that displays a generic error model with a title and a message?

于 2013-08-07T08:17:58.273 回答