如何以编程方式配置WCF绑定?

时间:2011-08-18 22:08:39

标签: wcf wcf-binding

我需要使用代码实现以下内容:

<basicHttpBinding>

        <binding name="NewBinding">

          <security mode="TransportCredentialOnly">

            <transport clientCredentialType="Basic" />

          </security>

        </binding>

      </basicHttpBinding>

有可用的样品吗?我正在研究WCF REST服务并手动注册路由。将此配置置于配置中不起作用。如果可能的话,我想以编程方式进行设置。另外,在代码的哪个阶段我应该这样做?

编辑:

我的服务在Global.asax中路由如下:

foreach (var account in cmc.Accounts.Where(aa => aa.IsActive).ToList())
                {
                    RouteTable.Routes.Add(
                        new ServiceRoute(
                            account.AccountId + "/mobile", new MyServiceHostFactory(), typeof(MobileService)));
                }

我有自己的ServiceHost

public class MyServiceHost : WebServiceHost
    {
        private readonly Type _serviceType;
        private readonly CompositionContainer _container;

        public MyServiceHost(Type serviceType, CompositionContainer container, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
            _serviceType = serviceType;
            _container = container;
        }

        protected override void OnOpening()
        {
            if (Description.Behaviors.Find<MyServiceBehavior>() == null)
            {
                Description.Behaviors.Add(new MyServiceBehavior(_serviceType, _container));
            }

            base.OnOpening();
        }
    }

1 个答案:

答案 0 :(得分:1)

对于这种特定情况,等效绑定如下:

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;