问题
I want to show custom error page when user tries to call controller methods which does not exist or authorization error occurs during access in MVC5 web application.
Is there any site which explains how to setup custom error page for MVC5 website.
Thanks in advance
回答1:
Check out this page by Ben Foster, very detailed explanation of the issues you will encounter and a solid solution. http://benfoster.io/blog/aspnet-mvc-custom-error-pages
回答2:
Add following <customErrors>
tag in the web.config that helps you to redirect to the NotFound
action method of Error
controller if the system fails to find the requested url (status code 404) and redirects to ServerError
action method of error controller if the system fires an internal server error (status code 500)
<!--<Redirect to error page>-->
<customErrors mode="On" defaultRedirect="~/Error/ServerError">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
<!--</Redirect to error page>-->
You have to create an Error
controller that contains ServerError
and NotFound
action method that renders the related view to display the proper message to the user.
public class ErrorController : Controller
{
public ActionResult NotFound()
{
return View();
}
public ActionResult Error()
{
return View();
}
}
回答3:
if you prefer you can handle errors in globalasax Application_Error() method like this:
protected void Application_Error(object sender, EventArgs e) {
var exception = Server.GetLastError();
Response.Clear();
string redirectUrl = "/Error"; // default
if (exception is HttpException) {
if (((HttpException)exception).GetHttpCode() == 404) {
redirectUrl += "/NotFound";
} else if (((HttpException)exception).GetHttpCode() == 401) {
redirectUrl += "/NotAuthorized";
} else {
redirectUrl += "?e=" + ((HttpException)exception).GetHttpCode();
}
Server.ClearError();
Response.Clear();
}
Response.Redirect(redirectUrl);
}
来源:https://stackoverflow.com/questions/25685737/mvc5-custom-error-page