WCF 项目中的 HttpModule 只工作一次



请考虑以下代码:

<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);

问题是在运行项目后,服务返回正确的结果,但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));

相关内容

  • 没有找到相关文章

最新更新