How to customize error pages in an ASP.NET MVC system?

10

How to display a friendlier page when an error occurs in my asp.net mvc application (and not that yellow page)?

    
asked by anonymous 13.12.2013 / 17:29

3 answers

8

There is a special view for these cases, Shared/Error.cshtml (this has to be this name).

Just plug in the customErrors of your application into Web.config :

<system.web>
    <customErrors mode="On" />
</system.web>

If you want to display error details, such as action name , a href="http://msdn.microsoft.com/library/system.web.mvc.handleerrorinfo.controllername.aspx"> controller name or a HandleErrorInfo .

The only problem is that, unfortunately, this solution does not address 404 errors (page not found). ASP.NET MVC does not support this type of error so easily.

To treat it you will need to write your own action for it (a URL of its own). Example, for URL ~/erros/nao-encontrado :

<customErrors mode="On">
  <error statusCode="404" redirect="~/erros/nao-encontrado" />
</customErrors>

In this case you are given the original URL via query string:

http://localhost/erros/nao-encontrado?aspxerrorpath=/administracao/algum-cadastro
    
13.12.2013 / 17:32
2

On my website I have modified Global.asax.cs and include

protected void Application_Error(object sender, EventArgs e)
{
    var app = (MvcApplication)sender;
    var context = app.Context;
    var ex = app.Server.GetLastError();
    context.Response.Clear();
    context.ClearError();

    var httpException = ex as HttpException;

    var routeData = new RouteData();
    routeData.Values["controller"] = "errors";
    routeData.Values["exception"] = ex;
    routeData.Values["action"] = "http500";

    if (httpException != null)
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                routeData.Values["action"] = "http404";
                break;
            case 500:
                routeData.Values["action"] = "http500";
                break;
        }
    }

    IController controller = new ErrorsController();
    controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
}

And I created a Controller to manage errors

public class ErrorsController : Controller
{
    public ActionResult Http404(Exception exception)
    {
        Response.StatusCode = 404;
        Response.ContentType = "text/html";
        return View(exception);
    }

    public ActionResult Http500(Exception exception)
    {
        Response.StatusCode = 500;
        Response.ContentType = "text/html";
        return View(exception);
    }
}

In this way if you access a nonexistent page you will be redirected to Action% with% of Controller% with%.

If you are trying to access an item (eg a product) and it does not exist, you can throw a 404 error.

Example URL: Http404

Produto x = db.GetProduto(10);

if (x == null)
    throw new HttpException(404, "Not Found");
    
14.12.2013 / 20:22
0

You can create an Error controler, returning to the Error view according to the generated error

   public class ErrorController : Controller
     {
       //Erro 500 Servidor
       public ActionResult Index()
       {
        ViewBag.AlertaErro = "Ocorreu um Erro :(";
        ViewBag.MensagemErro = "Tente novamente ou " +
            "contate um Administrador";

        return View("Error");
    }

    //Error 404
    public ActionResult NotFound()
    {
        ViewBag.AlertaErro = "Ocorreu um Erro :(";
        ViewBag.MensagemErro = "Não existe uma página para a URL informada";

        return View("Error");
    }


     //Erro 401 permissão de execução       
    public ActionResult AccessDenied()
    {
        //ViewBag.AlertaErro = "Acesso Negado :(";
        //ViewBag.MensagemErro = "Você não tem permissão para executar isso";

        return PartialView("Error403");
    }

Now in WebConfig, you enter this code:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="500" />
  <remove statusCode="404" />
  <remove statusCode="403" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error/Index" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <error statusCode="403" responseMode="ExecuteURL" path="/Error/AccessDenied" />
</httpErrors>

It is very easy to understand, in practice it replaces the standard error messages and will begin to use the ones that you have configured in the Controller

    
28.09.2018 / 18:55