Custom error pages on asp.net MVC3

前端 未结 6 1064
无人及你
无人及你 2020-11-22 11:07

I\'m developing a MVC3 base website and I am looking for a solution for handling errors and Render custom Views for each kind of error. So imagine that I have a \"Error\" Co

6条回答
  •  一个人的身影
    2020-11-22 11:44

    Here's an example of how I handle custom errors. I define an ErrorsController with actions handling different HTTP errors:

    public class ErrorsController : Controller
    {
        public ActionResult General(Exception exception)
        {
            return Content("General failure", "text/plain");
        }
    
        public ActionResult Http404()
        {
            return Content("Not found", "text/plain");
        }
    
        public ActionResult Http403()
        {
            return Content("Forbidden", "text/plain");
        }
    }
    

    and then I subscribe for the Application_Error in Global.asax and invoke this controller:

    protected void Application_Error()
    {
        var exception = Server.GetLastError();
        var httpException = exception as HttpException;
        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;
        Response.StatusCode = 500;
        if (httpException != null)
        {
            Response.StatusCode = httpException.GetHttpCode();
            switch (Response.StatusCode)
            {
                case 403:
                    routeData.Values["action"] = "Http403";
                    break;
                case 404:
                    routeData.Values["action"] = "Http404";
                    break;
            }
        }
    
        IController errorsController = new ErrorsController();
        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
        errorsController.Execute(rc);
    }
    

提交回复
热议问题