在ASP.NET MVC中返回404时创建自定义错误

时间:2016-09-06 04:07:01

标签: asp.net-mvc http-status-code-404 custom-errors

我试图搜索并找到一些解决方案。我尝试过但没有运气。大多数可接受的解决方案是配置我尝试过的Web.config文件,但它仍会返回默认错误页面

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

关于如何配置它的任何其他方式?

我不想在IIS中配置它

1 个答案:

答案 0 :(得分:2)

此解决方案不需要更改web.config文件或捕获所有路由。

首先,创建一个像这样的控制器;

public class ErrorController : Controller
{
public ActionResult Index()
{
    ViewBag.Title = "Regular Error";
    return View();
}

public ActionResult NotFound404()
{
    ViewBag.Title = "Error 404 - File not Found";
    return View("Index");
}
}

然后在“Views / Error / Index.cshtml”下创建视图;

 @{
  Layout = "~/Views/Shared/_Layout.cshtml";
 }                     
<p>We're sorry, page you're looking for is, sadly, not here.</p>

然后在Global asax文件中添加以下内容:

protected void Application_Error(object sender, EventArgs e)
    {
    // Do whatever you want to do with the error

    //Show the custom error page...
    Server.ClearError(); 
    var routeData = new RouteData();
    routeData.Values["controller"] = "Error";

    if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
    {
        routeData.Values["action"] = "Index";
    }
    else
    {
        // Handle 404 error and response code
        Response.StatusCode = 404;
        routeData.Values["action"] = "NotFound404";
    } 
    Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
    IController errorsController = new ErrorController();
    HttpContextWrapper wrapper = new HttpContextWrapper(Context);
    var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
    errorsController.Execute(rc);
 }

如果在执行此操作后仍然出现自定义IIS错误页面,请确保在Web配置文件中注释掉(或清空)以下部分:

   <system.web>
    <customErrors mode="Off" />
   </system.web>
   <system.webServer>   
    <httpErrors>     
    </httpErrors>
   </system.webServer>