C# 遇到异常时呈现错误视图

C# 遇到异常时呈现错误视图,c#,asp.net-mvc,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 Proper

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

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
控制器/SomeAction/NotFoundId
将引发异常。我讨厌在项目中有这样的东西:
~/Views/Shared/NotFound.cshtml

使其成为一个显示带有标题和消息的通用错误模型的
“~/Views/Shared/Error.cshtml”
。您可以将HttpNotFoundResult对象返回为:

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


我意识到这个问题已经有几年历史了,但我想我应该补充一下公认的答案。按照CodeCaster的建议,使用标准的“Error.cshtml”作为文件(视图)作为通用错误页面,我建议您让MVC框架为您完成其余的工作

如果将Error.cshtml文件放在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("Error", NotFoundViewModel);
    }
}

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

Just return a 404的副本?它毕竟找不到。这看起来不错。我必须有一个错误控制器,这样我才能返回重定向到Action,并将NotFoundAction和我的NotFoundViewModel作为参数。在NotFoundAction中,我将呈现我的NotFoundView。可以吗?或者看一看。
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);
    }
}