How to make custom error pages work in ASP.NET MVC 4

前端 未结 11 2117
陌清茗
陌清茗 2020-11-22 12:25

I want a custom error page shown for 500, 404 and 403. Here\'s what I have done:

  1. Enabled custom errors in the web.config as follows:

    
    
            
11条回答
  •  失恋的感觉
    2020-11-22 13:22

    My current setup (on MVC3, but I think it still applies) relies on having an ErrorController, so I use:

    
        
          
        
    
    

    And the controller contains the following:

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

    And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this:

    @model System.Web.Mvc.HandleErrorInfo
    @{
        Layout = "_Layout.cshtml";
        ViewBag.Title = "Error";
    }
    
    Error
    An unexpected error has occurred. Please contact the system administrator.
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled) {

    Exception: @Model.Exception.Message
    Controller: @Model.ControllerName
    Action: @Model.ActionName

                        @Model.Exception.StackTrace
                    
    }

提交回复
热议问题