Kees C. Bakker
Kees C. Bakker

Reputation: 33381

How to end request with 404 in an IHttpModule?

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?

Upvotes: 1

Views: 3921

Answers (4)

Kees C. Bakker
Kees C. Bakker

Reputation: 33381

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.

Upvotes: 2

Rohit Vyas
Rohit Vyas

Reputation: 1969

You can explicitly set the status code to 404 like:

HttpContext.Current.Response.StatusCode = 404; 
HttpContext.Current.Response.End();

Response will stop executing.

Upvotes: 3

Pal R
Pal R

Reputation: 534

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.

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with

throw new HttpException(404, "File Not Found");

Upvotes: 1

Related Questions