Create custom error when it returns 404 in ASP.NET MVC

徘徊边缘 提交于 2019-12-11 01:23:08

问题


I've tried to search and found some solution on it. I tried it on but no luck. Most of the accepted solution is to configure your Web.config file I tried it but it still return the default error page

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

any other way on how to configure it?

I don't want to configure it in IIS


回答1:


This solution doesn't need web.config file changes or catch-all routes.

First, create a controller like this;

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");
}
}

Then create the view under "Views/Error/Index.cshtml" as;

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

Then add the following in the Global asax file as below:

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);
 }

If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:

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


来源:https://stackoverflow.com/questions/39340494/create-custom-error-when-it-returns-404-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!