web.config
Turn off custom errors in system.web
<system.web>
<customErrors mode="Off" />
</system.web>
configure http errors in system.webServer
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Auto">
<clear />
<error statusCode="404" responseMode="ExecuteURL" path="/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
</system.webServer>
Create simple error controller to handle those requests ErrorContoller.cs
[AllowAnonymous]
public class ErrorController : Controller {
// GET: Error
public ActionResult NotFound() {
var statusCode = (int)System.Net.HttpStatusCode.NotFound;
Response.StatusCode = statusCode;
Response.TrySkipIisCustomErrors = true;
HttpContext.Response.StatusCode = statusCode;
HttpContext.Response.TrySkipIisCustomErrors = true;
return View();
}
public ActionResult Error() {
Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
Response.TrySkipIisCustomErrors = true;
return View();
}
}
configure routes RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes) {
//...other routes
routes.MapRoute(
name: "404-NotFound",
url: "NotFound",
defaults: new { controller = "Error", action = "NotFound" }
);
routes.MapRoute(
name: "500-Error",
url: "Error",
defaults: new { controller = "Error", action = "Error" }
);
//..other routes
//I also put a catch all mapping as last route
//Catch All InValid (NotFound) Routes
routes.MapRoute(
name: "NotFound",
url: "{*url}",
defaults: new { controller = "Error", action = "NotFound" }
);
}
And finally make sure you have views for the controller actions
Views/Shared/NotFound.cshtml
Views/Shared/Error.cshtml
If there are any additional error you want to handle you can follow that pattern and add as needed. This will avoid redirects and maintain the original http error status that was raised.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…