簡體   English   中英

遇到異常時渲染錯誤視圖

[英]Render error view when we encounter an exception

我怎么能以另一種方式做到這一點?

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

我意識到這個問題已經有幾年了,但我想我會加入已接受的答案。 遵循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消息:(

您可以將HttpNotFoundResult對象返回為:

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

要么

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

使它成為"~/Views/Shared/Error.cshtml" ,顯示帶有標題和消息的通用錯誤模型?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM