我怎样才能用另一种方式做到这一点?
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。
小智 5
我意识到这个问题已经有几年了,但我想我应该添加到已接受的答案中。按照 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 消息:(
| 归档时间: | 
 | 
| 查看次数: | 16914 次 | 
| 最近记录: |