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

Asp.net mvc 在ASP.NET MVC中返回404时创建自定义错误,asp.net-mvc,http-status-code-404,custom-errors,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.config
文件。我尝试了它,但它仍然返回默认错误页

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

关于如何配置它,还有其他方法吗


我不想在IIS中配置它

此解决方案不需要更改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”下创建视图,如下所示

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

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


嗨!我尝试了您建议的工作方式,但我现在的问题是
\u布局中的代码。cshtml
已被放置到
而不是您使用的
routeData
,我使用了
Response.Redirect(~/Error/Index”)
及其工作原理。Thanks@FrostyPinky不客气,很高兴我能帮忙:)
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);
 }
   <system.web>
    <customErrors mode="Off" />
   </system.web>
   <system.webServer>   
    <httpErrors>     
    </httpErrors>
   </system.webServer>