Custom error pages on asp.net MVC3

前端 未结 6 934
无人及你
无人及你 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:40

    I'm using MVC 4.5 and I was having issues with Darin's solution. Note: Darin's solution is excellent and I used it to come up with my solution. Here's my modified solution:

    protected void Application_Error(object sender, EventArgs e)
    {           
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;
    Response.StatusCode = httpException.GetHttpCode();
    
    Response.Clear();
    Server.ClearError();
    
    
    if (httpException != null)
    {
        var httpContext = HttpContext.Current;
    
        httpContext.RewritePath("/Errors/InternalError", false);
    
        // MVC 3 running on IIS 7+
        if (HttpRuntime.UsingIntegratedPipeline)
        {
            switch (Response.StatusCode)
            {
                case 403:
                    httpContext.Server.TransferRequest("/Errors/Http403", true);
                    break;
                case 404:
                    httpContext.Server.TransferRequest("/Errors/Http404", true);
                    break;
                default:
                    httpContext.Server.TransferRequest("/Errors/InternalError", true);
                    break;
            }
        }
        else
        {
            switch (Response.StatusCode)
            {
                case 403:
                    httpContext.RewritePath(string.Format("/Errors/Http403", true));
                    break;
                case 404:
                    httpContext.RewritePath(string.Format("/Errors/Http404", true));
                    break;
                default:
                    httpContext.RewritePath(string.Format("/Errors/InternalError", true));
                    break;
            }
    
            IHttpHandler httpHandler = new MvcHttpHandler();
            httpHandler.ProcessRequest(httpContext);
        }
    }
    }
    

提交回复
热议问题