13

I have created a Asp.net MVC application. Now required 404 handling.

Have updated global.asax and display 404 page based on status code. Also added customErrors property in web.config. Its working fine.

Now I would like to redirect to 404 programmatically when any thing not match with our requirement.

i.e.

if(!valid) 
{
    return RedirectToAction("Index", "Page404");
}

It's working fine but there are 2 status one is 301 & then 404. So how can I prevent 301? I just need 404.

How can I achieve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Laxmi Lal Menaria
  • 1,433
  • 4
  • 17
  • 30

3 Answers3

45

Simply return from your action:

return HttpNotFound();
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
jorgehmv
  • 3,633
  • 3
  • 25
  • 39
  • 2
    This is the correct answer. In a case where you query the database whilst servicing a result, and find an object with the user-specified ID does not exist, you DO need to programmatically redirect the user to a 404 page (or similar action). – Dermot Nov 13 '13 at 01:41
4

In your web.config, add:

<customErrors mode="On" >
       <error statusCode="404" redirect="/404.shtml" />
</customErrors>

This will redirect on 404.shtml page when requested resource is not found.

Note: No need to programmatically redirect users for such situation.


EDIT: I literally suggest:

if (Context.Response.StatusCode == 404) {
  // handle this
}
Vishal
  • 2,161
  • 14
  • 25
2

Just throw out a 404 in the status code:

Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound
web_bod
  • 5,728
  • 1
  • 17
  • 25