2012-10-29 37 views
1

我在寫一個新的IHttpModule。我想使用BeginRequest事件處理程序使404的某些請求無效。我如何終止請求並返回404?如何在IHttpModule中使用404結束請求?

+0

這有你的答案:http://stackoverflow.com/questions/499817/what-is-the-proper-way-to-send-an-http-404 -response-from-an-asp-net-mvc-action - 拋出一個HttpException – MatthewMartin

回答

1

您可以在狀態代碼明確設置爲404,如:

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

響應將停止執行。

1

您可以

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

爲什麼拋出比只做一個'Response.StatusCode = 404; Response.End()'? –

+0

如果你想IIS生成的html通常伴隨404,使用例外 – agradl

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頁。

+0

會''Response.StatusCode = 404;'不夠? –

+0

我相信你將不得不結束迴應... –

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. 
相關問題