如何在IHttpModule中用404结束请求?

时间:2012-10-29 12:56:51

标签: c# asp.net httpmodule

我正在写一个新的IHttpModule。我想使用BeginRequest事件处理程序使404无效某些请求。如何终止请求并返回404?

4 个答案:

答案 0 :(得分:3)

您可以将状态代码显式设置为404,如:

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

响应将停止执行。

答案 1 :(得分:1)

您可以尝试使用

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

答案 2 :(得分:1)

另一种可能性是:

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.

答案 3 :(得分:0)

您可以执行以下操作:

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Location", l_notFoundPageUrl);
HttpContext.Current.Response.Status = "404 Not Found";
HttpContext.Current.Response.End();

将l_notFoundPageUrl分配到404页面。