bluray
bluray

Reputation: 1953

ASP MVC redirect to error page from controller

I have a simple question. How to redirect from controller to custom error page with http status code? For example:

public ActionResult Index()
{
   this.Redirect("Not found", 404); //redirect to my error page with code 404
}

Upvotes: 6

Views: 21144

Answers (1)

Sarika Koli
Sarika Koli

Reputation: 783

add this code in web.config file:-

<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
  <error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>

Add below code in controller:

public class ErrorController : Controller{
public ViewResult Index()
{
    return View("Error");
}
public ViewResult NotFound()
{
    Response.StatusCode = 404;  //you may want to set this to 200
    return View("NotFound");
}}

Upvotes: 11

Related Questions