WCF 项目中的 HttpModule 只工作一次

HttpModule in WCF project just works once

请考虑此代码:

<system.web>
    <compilation debug="true" targetFramework="4.6"/>
    <httpRuntime targetFramework="4.5.2"/>
   <authentication mode="None" />
  </system.web>
  <system.serviceModel>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

     <services>
      <service name="MyNameSpace.Services.Service1" behaviorConfiguration="ServiceBehavior">

        <endpoint  binding="basicHttpBinding"  contract="MyNameSpace.Services.ISrv"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpBinding" scheme="http"/>
    </protocolMapping>
    </system.serviceModel>
        <system.webServer>
            <modules runAllManagedModulesForAllRequests="true">
                <add name="AuthSecurity" type="MyNameSpace.CustomAuthorization"  />
            </modules>
        <directoryBrowse enabled="true"/>
    </system.webServer>

并且 HttpModule 代码是:

namespace MyNameSpace
{
    public class CustomAuthorization : IHttpModule
    {
        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
           CheckAccess();
        }

        private bool CheckAccess()
        {
            HttpContext c = HttpContext.Current;

            if (HttpContext.Current.Handler != null)   // <--Break Point
            {
                string authHeader = HttpContext.Current.Request.Headers["Authorization"];
                ...
            } 
            return false;
        }
    }
}

在客户端我写了这段代码:

Service1client client = new Service1client();

client.ClientCredentials.UserName.UserName = "mmmm"
client.ClientCredentials.UserName.Password = "nnnn";

var tmp = client.DoWork(1);

问题是在 运行 项目之后,服务 returns 正确的结果但是 HttpModule 代码没有执行。

当我在 HttpModule 中使用断点时,它会在 Application_Start 事件期间触发。但在那之后它不再命中并且它的代码不执行。

问题出在哪里?

谢谢

据我了解,您定义了应用程序启动时要执行的操作;如果您想检查传入的请求,请尝试将这些方法添加到您的 HttpModule 并设置断点以检查这些方法是否被命中:

private void Application_BeginRequest(Object source, 
         EventArgs e)
    {
         CheckAccess();
    }

    private void Application_EndRequest(Object source, EventArgs e)
    {
         CheckAccess();
    }

当然你需要在应用程序启动时注册这些方法:

        application.BeginRequest += 
        (new EventHandler(this.Application_BeginRequest));
    application.EndRequest += 
        (new EventHandler(this.Application_EndRequest));