How to customize error 404 using Httpnotfound?

Asked

Viewed 218 times

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:

inserir a descrição da imagem aqui

Here is path: Views/404/404.cshtml

Some solution ?

  • You’re testing the place?

  • Switch to customErrors mode="On"

  • See the answer.

1 answer

3


So you can test locally, the mode of customErrors needs to be On. That’s because the RemoteOnly only serves to make these pages appear outside the development environment.

I’m not sure if the redirect can be directly a CSHTML page, I think not, even because it would not make sense.

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

I think this second way is much better, because it follows a pattern (possibly your whole project is like this) and leaves everything more dynamic, in case it is necessary to customize the message or related.

Note: Remove the redirectMode="ResponseRewrite" if you’re going to use it this way.

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

And make a controller normal to receive this request.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.