I'm writing a new IHttpModule. I would like to invalidate certain requests with 404 using a BeginRequest
event handler. How do I terminate the request and return a 404?
Asked
Active
Viewed 3,795 times
1

Kees C. Bakker
- 32,294
- 27
- 115
- 203
-
This has your answer: http://stackoverflow.com/questions/499817/what-is-the-proper-way-to-send-an-http-404-response-from-an-asp-net-mvc-action -- throw an HttpException – MatthewMartin Oct 29 '12 at 13:04
4 Answers
3
You can explicitly set the status code to 404 like:
HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.End();
Response will stop executing.

Kees C. Bakker
- 32,294
- 27
- 115
- 203

Rohit Vyas
- 1,949
- 3
- 19
- 28
1
You can try with
throw new HttpException(404, "File Not Found");

Aghilas Yakoub
- 28,516
- 5
- 46
- 51
-
Why would throwing be better than just doing a `Response.StatusCode = 404; Response.End()` ? – Kees C. Bakker Oct 29 '12 at 18:43
-
If you want the IIS generated html that usually accompanies a 404, use the exception – agradl May 07 '15 at 19:07
1
Another possibility is:
HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

Kees C. Bakker
- 32,294
- 27
- 115
- 203
0
You can do the following:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Location", l_notFoundPageUrl);
HttpContext.Current.Response.Status = "404 Not Found";
HttpContext.Current.Response.End();
Assign l_notFoundPageUrl to your 404 page.

Pal R
- 534
- 4
- 11