拒绝http动词:system.web.httpmethodnotallowedhandler从未被调用



在我的网站上,我想禁止HTTP HEAD请求,并通过405状态代码(Method not allowed(回答它们。为此,我在web.config文件中有以下内容:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="TelemetryCorrelationHttpModule" />
    <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
    <remove name="ApplicationInsightsWebTracking" />
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
  </modules>
  <handlers>
    <clear />
    <add name="DenyHead" path="*" verb="HEAD" type="System.Web.HttpMethodNotAllowedHandler" />
    <add name="DebugAttachHandler" path="DebugAttach.aspx" verb="DEBUG" type="System.Web.HttpDebugHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
  <security>
    <requestFiltering allowDoubleEscaping="true">
      <verbs allowUnlisted="false">
        <add verb="GET" allowed="true" />
        <add verb="POST" allowed="true" />
        <add verb="HEAD" allowed="true" />
        <add verb="DEBUG" allowed="true" />
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

不幸的是,这不起作用 - 我正在接收沼泽标准404。

启用失败的请求跟踪会产生以下内容:

20  HANDLER_CHANGED OldHandlerName
                    NewHandlerName DenyHead
                    NewHandlerType System.Web.HttpMethodNotAllowedHandler
...
61  AspNetPipelineEnter Data1 <Application_BeginRequest in my ASP.NET application>
...
135 HANDLER_CHANGED OldHandlerName System.Web.HttpMethodNotAllowedHandler
                    NewHandlerName System.Web.Mvc.MvcHandler
...
169 MODULE_SET_RESPONSE_ERROR_STATUS Notification EXECUTE_REQUEST_HANDLER
                                     HttpStatus   404

这似乎表明DenyHead处理程序在某种程度上被我的MVC应用程序替换/覆盖,但是我的应用程序中没有代码可以执行任何操作。

我尝试了其他建议,例如答案,但是它们给出了相同的结果。

  • 请求过滤不是选项,因为它返回的状态代码无法配置(它总是返回404(。
  • 操作过滤器不是一个选项,因为它们不会被静态内容击中,而且我不想通过MVC管道发送所有内容。

您可以创建动作过滤器,并检查请求方法。如果是"头",则可以通过" filterContext"上的设置结果属性拒绝请求,并将状态代码设置为405方法。

或者您可以在global.aspx中查看上面的logic_beginrequest并执行相同的操作。

我不会使用IIS配置,因为它可以使您依赖于IIS,即使您可能已经存在。使用过滤器消除了依赖性,就像这样:

public class VerbFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (context.HttpContext.Request.Method == "HEAD")
        {
            context.Result = new StatusCodeResult(405);
        }
        else
        {
            await next();
        }
    }
}

最新更新