MVC3 Custom Error Pages work in dev, not on server

2020-03-07 07:00发布

问题:

I am using the solution detailed in this SO Question. I've used this on other sites before and its worked fine, and it works on my dev box. However, when I publish to a our Windows VPS, errors return the standard IIS error page.

I have never administered a web server before, and I am not sure what settings I need to check to figure out why its not returning the custom errors I have set up. I have tried setting .net error pages for the app to off and on, with the default page set to the root site, as well as just '/'.

I have also tried setting the error pages (under iis in 7.5) to custom and detailed.

None of these seem to have any effect on the error page that is returned. What am I doing wrong here?

回答1:

I remember having similar problem and I added this line to the code

 protected void Application_Error()
 {
 var exc = Server.GetLastError();
 var httpExc = exc as HttpException;
 Response.Clear();
 Server.ClearError();
 var routeData = new RouteData();
 routeData.Values["controller"] = "Error";
 routeData.Values["action"] = "General";
 routeData.Values["exception"] = exc;
 Response.StatusCode = 500;
 if (httpExc != null)
 {
     Response.StatusCode = httpExc.GetHttpCode();
     routeData.Values["action"] = "Http404";
     routeData.Values["exception"] = httpExc;
 }
 Response.TrySkipIisCustomErrors = true; //this fixed it
 IController errorsController = new WWS_Website.Controllers.ErrorController();
 var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
 errorsController.Execute(rc);

 }


回答2:

You can replace the standard IIS error pages by using the httpErrors section in the system.webServer section in your web.config file. This is in addition to the customErrors section in system.web.

<system.webServer>
    ...
    <httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
        <remove statusCode="400" subStatusCode="-1" />
        <error statusCode="400" prefixLanguageFilePath="" 
            path="/errors/400" responseMode="ExecuteURL" />
        <remove statusCode="404" subStatusCode="13" />
        <error statusCode="404" subStatusCode="13" prefixLanguageFilePath=""
            path="/errors/file-upload-too-large" responseMode="Redirect" />
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" 
            path="/errors/404" responseMode="ExecuteURL" />
        <remove statusCode="403" subStatusCode="-1" />
        <error statusCode="403" prefixLanguageFilePath="" 
            path="/errors/403" responseMode="ExecuteURL" />
    </httpErrors>