繁体   English   中英

使用ClientBase调用WCF服务时如何设置EndpointBehaviors名称

[英]How to set endpointBehaviors name when calling wcf service using ClientBase

我在数据库的客户端端点不在web.config中。 我正在使用ClientBase,它具有构造函数的数量,可以在其中传递绑定,地址等。并且可以调用客户端wcf服务。 我在web.config中定义了绑定配置和行为配置。 使用ClientBase时可以传递这些名称。 但是我找不到该类的任何属性或构造函数,无法传递在web.config中已定义的EndpointBehavior名称。 我可以看到我可以添加IEndpointBehavior实例,但是我不想使用它,而是更喜欢只传递在web.config中定义的endpointbehavior名称。

任何帮助,将不胜感激。

谢谢。

我认为没有一种方法可以让您仅使用行为名称。 作为此处的工作,您有一些方法可以从配置加载设置,创建IEndpointBehaviours并将其添加到服务端点。

using System.Configuration;
using System.ServiceModel.Configuration;

    public static void ApplyEndpointBehavior(ServiceEndpoint serviceEndpoint, string behaviorName)
    {
        EndpointBehaviorElement endpointBehaviorElement = GetEndpointBehaviorElement(behaviorName);
        if (endpointBehaviorElement == null) return;

        List<IEndpointBehavior> list = CreateBehaviors<IEndpointBehavior>(endpointBehaviorElement);

        foreach (IEndpointBehavior behavior in list)
        {
            Type behaviorType = behavior.GetType();
            if (serviceEndpoint.Behaviors.Contains(behaviorType))
            {
                serviceEndpoint.Behaviors.Remove(behaviorType);
            }
            serviceEndpoint.Behaviors.Add(behavior);
        }
    }

    public static EndpointBehaviorElement GetEndpointBehaviorElement(string behaviorName)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ServiceModelSectionGroup sectionGroup = ServiceModelSectionGroup.GetSectionGroup(config);
        if (sectionGroup == null || !sectionGroup.Behaviors.EndpointBehaviors.ContainsKey(behaviorName))
            return null;

        return sectionGroup.Behaviors.EndpointBehaviors[behaviorName];
    }

    public static List<T> CreateBehaviors<T>(EndpointBehaviorElement behaviorElement) where T : class
    {
        List<T> list = new List<T>();
        foreach (BehaviorExtensionElement behaviorSection in behaviorElement)
        {
            MethodInfo info = behaviorSection.GetType().GetMethod("CreateBehavior", BindingFlags.NonPublic | BindingFlags.Instance);
            T behavior = info.Invoke(behaviorSection, null) as T;
            if (behavior != null)
            {
                list.Add(behavior);
            }
        }
        return list;
    }

请注意,虽然它有点笨拙,但是它使用受保护的方法来实例化行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM