You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF调用WCF服务时无法触发ApplyClientBehavior方法求助

WPF调用WCF时ApplyClientBehavior不触发的解决方法

1. 补全CustomBehaviorExtensionElement实现

配置中引用的CustomBehaviorExtensionElement是连接配置与AuthorizationHeaderEndpointBehavior的核心桥梁,必须正确实现该类:

using System.ServiceModel.Configuration;

namespace Utils.CMSAuth
{
    public class CustomBehaviorExtensionElement : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get { return typeof(AuthorizationHeaderEndpointBehavior); }
        }

        protected override object CreateBehavior()
        {
            return new AuthorizationHeaderEndpointBehavior();
        }
    }
}

2. 完善客户端配置,关联行为到端点

仅注册行为扩展不足以触发行为,需要在配置中把自定义行为绑定到客户端端点:

在WPF项目的app.config中补充以下配置:

<system.serviceModel>
  <!-- 保留已有的extensions配置 -->
  <extensions>
    <behaviorExtensions>
      <add name="AuthorizationHeaderMessageInspector" 
           type="Utils.CMSAuth.CustomBehaviorExtensionElement, Utils, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </behaviorExtensions>
  </extensions>

  <!-- 添加端点行为配置 -->
  <behaviors>
    <endpointBehaviors>
      <behavior name="AuthHeaderBehavior">
        <AuthorizationHeaderMessageInspector />
      </behavior>
    </endpointBehaviors>
  </behaviors>

  <!-- 客户端端点指定行为 -->
  <client>
    <endpoint 
      address="你的WCF服务地址" 
      binding="basicHttpBinding" 
      contract="你的服务契约接口"
      behaviorConfiguration="AuthHeaderBehavior" />
  </client>
</system.serviceModel>

3. 校验程序集信息一致性

确认配置中type属性的程序集信息与Utils项目实际信息匹配:

  • 右键Utils项目 → 属性 → 应用程序 → 程序集信息,查看版本、公钥标记(无强命名则为null)
  • 若程序集版本更新,同步修改配置中的Version值

4. 代码配置场景的手动行为添加

如果是通过代码手动创建WCF客户端而非依赖配置文件,需手动将行为添加到端点:

var wcfClient = new YourWcfServiceClient();
wcfClient.Endpoint.Behaviors.Add(new AuthorizationHeaderEndpointBehavior());
// 调用服务方法
wcfClient.TargetServiceMethod();

内容的提问来源于stack exchange,提问作者Padmaja Nory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 22:46:26