2017-01-30 85 views
0

我有一個簡單的問題。如何使用http狀態碼從控制器重定向到自定義錯誤頁面? 例如:ASP MVC重定向到控制器的錯誤頁面

public ActionResult Index() 
{ 
    this.Redirect("Not found", 404); //redirect to my error page with code 404 
} 
+0

只返回視圖, return View(「view name」); – Balu

+0

返回'new HttpNotFoundResult()',然後使用內置的錯誤處理。 –

回答

4

在web.config文件中添加以下代碼: -

<system.web> 
<customErrors mode="On" defaultRedirect="~/Error"> 
    <error redirect="~/Error/NotFound" statusCode="404" /> 
</customErrors> 

添加以下代碼控制器:

public class ErrorController : Controller{ 
public ViewResult Index() 
{ 
    return View("Error"); 
} 
public ViewResult NotFound() 
{ 
    Response.StatusCode = 404; //you may want to set this to 200 
    return View("NotFound"); 
}}