【问题标题】:How to end request with 404 in an IHttpModule?如何在 IHttpModule 中以 404 结束请求?
【发布时间】:2012-10-18 19:07:20
【问题描述】:

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

【问题讨论】:

标签: c# asp.net httpmodule


【解决方案1】:

你可以试试

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

【讨论】:

  • 为什么投掷比Response.StatusCode = 404; Response.End() 更好?
  • 如果你想要IIS生成的通常伴随404的html,使用异常
【解决方案2】:

您可以执行以下操作:

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 页面。

【讨论】:

  • Response.StatusCode = 404; 还不够吗?
【解决方案3】:

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

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

响应将停止执行。

【讨论】:

    【解决方案4】:

    另一种可能是:

    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多