1

In the ASPX project I am now converting to MVC 4 Razor the custom 404 error page had a few lines of code executed inside the OnLoad event but my understanding of the MVC razor platform this event no longer exists so I am not sure where I would run this code at.

Here is the code from my ASPX page that I want to translate into a razor page that will handle my 404 events.

protected override void OnLoad(EventArgs e)
{
    Response.TrySkipIisCustomErrors = true;
    Response.Status = "404 Not FOund";
    Response.StatusCode = 404;
    base.OnLoad(e);
}
  • 2
    When you convert a WebForms app to MVC, you can't just line by line convert, you have to convert concepts as well. What are you trying to do exactly with this code? There is probably a different way to do it in MVC. – Erik Funkenbusch Jun 17 '13 at 03:12
  • **Duplicate** of [How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller](http://stackoverflow.com/questions/5072804/how-to-return-a-200-http-status-code-from-asp-net-mvc-3-controller). – CodeCaster Jun 17 '13 at 09:26
  • Please, stop thinking in "web forms" way. MVC is a completely different beast. It's not an event based way of programming. Change your mind!! – JotaBe Jun 17 '13 at 10:03

2 Answers2

0

Try this...

public ActionResult Index() {        
    throw new HttpException(404, "Page Not Found");
}

Edit, this might be better for your situation.

public ActionResult Index() { 
    return new HttpStatusCodeResult(HttpStatusCode.NotFound, "Page Not Found");
}

This discussion has better explanation: https://stackoverflow.com/a/4985562/193634

Community
  • 1
  • 1
Rosdi Kasim
  • 24,267
  • 23
  • 130
  • 154
  • Hi, I am away from my PC right now, can't test.. but can you try putting the code in your Razor view instead? See the new code sample above. – Rosdi Kasim Jun 17 '13 at 02:56
  • 1
    This is by design. An actual 404 is sent only for completely unhandled URLs or files that physically don't exist. 404s from actions still return code 200 with textual "not found" errors only. This is because practically every browser hijacks 404 errors and displays their own error page. To keep the UX consistent, the web site returns a normal page with a textual error message. To force a 404 you'll need to set the HTTP status manually instead of simply throwing a HttpException. – Monstieur Jun 17 '13 at 04:59
  • The SO post you linked lead me to this http://blogs.microsoft.co.il/blogs/shay/archive/2009/03/06/real-world-error-hadnling-in-asp-net-mvc-rc2.aspx which looks to be what I want. –  Jun 18 '13 at 00:32
  • I am glad you found what you were looking for. – Rosdi Kasim Jun 18 '13 at 04:40
-1

This is setting 404 for me:

public ActionResult Index() {
  Response.Status = "404 Not Found";
  Response.StatusCode = 404;
  return null;
}
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89