How to customize the 404 error using HttpNotFound?

0

Follow the code below:

Controller:

if (id == null)
{
    //Response.StatusCode = 404;
    return HttpNotFound();
}

View:

@{
    Layout = null;
}

<h2>Página não encontrada</h2>

I added new code web.config:

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="/404.cshtml" />
</customErrors>

Final result:

Here is path: Views / 404 / 404.cshtml

Any solution?

    
asked by anonymous 14.02.2017 / 16:33

1 answer

3

To be able to test locally, mode of customErrors must be On . This is because RemoteOnly is just for these pages to appear outside of the development environment.

I'm not sure if redirect can be directly a CSHTML page, I do not think so, because it would not make sense.

If you're going to use a completely static page, use an HTML page yourself. If you need server data, redirect to an action within a controller .

I think this second form is much better, even because it follows a pattern (possibly your whole project is like this) and leaves everything more dynamic if you need to customize the message or the like.

Note: remove redirectMode="ResponseRewrite" if you use it this way.

<customErrors mode="RemoteOnly">
  <error statusCode="404" redirect="~/Erro/NaoEncontrado" />
</customErrors>

And make a normal controller to receive this request.

public class ErroController : Controller
{
    public ActionResult NaoEncontrado()
    {
        return View("CaminhoDaView");
    }
}
    
14.02.2017 / 16:40