Answer Detail

How to return 404 or 500 with asp.net mvc view?

Stevan
Stevan
18 Points
9 Posts

I'm using custom error handling:

<customErrors mode="On" defaultRedirect="Error/Error">
            <error statusCode="400" redirect="Error/Error" />
            <error statusCode="404" redirect="Error/NotFound" />
        </customErrors>

In controller actions:

public class ErrorController : Controller
    {
        public ActionResult Error()
        {          
            return View();
        }
        public ActionResult NotFound()
        {
            return View();
        }
    }

It's returning the view with 200 http header. I want response code with 404 or 500.

Total Answered: 2
Total Marked As Answer: 0
Posted On: 25-Dec-2018 21:12

Share:   fb twitter linkedin
Answers
edx
edx
34 Points
12 Posts
     

Just add following line before return view():

 Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
public class ErrorController : Controller
    {
        public ActionResult Error()
        {        
            Response.StatusCode = 404;
            Response.TrySkipIisCustomErrors = true;  
            return View();
        }
        public ActionResult NotFound()
        {
            Response.StatusCode = 404;
            Response.TrySkipIisCustomErrors = true;
            return View();
        }
    }
Posted On: 26-Dec-2018 01:03
sid
sid
18 Points
9 Posts
     
if (something == null)
{        
   return new HttpNotFoundResult(); // 404
}
elese if (something == "error")
{        
   return new HHttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError); // 500
}
else
{
   return new HttpStatusCodeResult(HttpStatusCode.OK); // 200
}
Posted On: 26-Dec-2018 01:34
banner

Blog

Active User (1)

 Log In to Chat