MVC5 custom error page

五迷三道 提交于 2019-12-11 03:36:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!