3
When using the class HttpStatusCodeResult
as a return to a Action
, how do I redirect the user to a custom page according to the error?
3
When using the class HttpStatusCodeResult
as a return to a Action
, how do I redirect the user to a custom page according to the error?
1
There are several ways to do this, you can in the action itself identify the error and redirect, you can also use global.asx but I recommend you use web.config to do this.
<configuration>
<system.web>
<customErrors mode="On">
<error statusCode="400" redirect="~/400"/>
</customErrors>
</system.web>
</configuration>
Create the route, controller and view for the error page you want to display.
routes.MapRoute(
"404",
"404",
new { controller = "Commons", action = "HttpStatus404" }
);
Controller
public ActionResult HttpStatus404()
{
return View();
}
Source: https://stackoverflow.com/questions/5635114/returning-404-error-asp-net-mvc-3
1
Set in your file web.config
the pages to be returned for each error code.
<configuration>
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite">
<error code="404" path="404.html" />
<error code="500" path="500.html" />
</customErrors>
</system.web>
</configuration>
Entries do not need to be static. They can even be returned by Views of Controllers specific.
The redirectMode
makes the answer really the desired code. The problem with default redirecting is that redirecting makes the redirect page return with code 200 (OK), which is wrong.
Browser other questions tagged c# asp.net-mvc
You are not signed in. Login or sign up in order to post.
And if even I add the
customErrors
in myweb.config
, as well as you published, only changing thepath
forredirect
, and it still doesn’t work?– Pablo Tondolo de Vargas
The @Paulohdsousa response has something about route configuration. I didn’t think it was necessary to put part of his answer in my.
– Leonel Sanches da Silva