WCF项目中的HttpModule只运行一次

时间:2018-03-08 12:41:05

标签: c# web-services wcf httpmodule basichttpbinding

请考虑以下代码:

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

问题是在运行项目后,Service返回正确的结果,但HttpModule代码没有执行。

当我在HttpModule中使用断点时,它会在 Application_Start 事件期间点击。但在此之后它不会再出现,而且它的代码也不会执行。

问题出在哪里?

由于

1 个答案:

答案 0 :(得分:0)

据我所知,你定义了在应用程序启动时要做什么;如果要检查传入的请求,请尝试将这些方法添加到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));