Set WCF ClientCredentials in App.config

后端 未结 4 1948
逝去的感伤
逝去的感伤 2020-12-30 08:40

Is it possible to set clientcredentials for an WCF in App.config?

I would like to avoid doing this:

Using svc As New MyServiceClient
  svc.ClientCre         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 09:02

    Expanding on Ladislav Mrnka’s answer, you might find this implementation useful:

    public class UserNameClientCredentials : ClientCredentialsElement
    {
        private ConfigurationPropertyCollection properties;
    
        public override Type BehaviorType
        {
            get { return typeof (ClientCredentials); }
        }
    
        /// 
        /// Username (required)
        /// 
        public string UserName
        {
            get { return (string) base["userName"]; }
            set { base["userName"] = value; }
        }
    
        /// 
        /// Password (optional)
        /// 
        public string Password
        {
            get { return (string) base["password"]; }
            set { base["password"] = value; }
        }
    
        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                if (properties == null)
                {
                    ConfigurationPropertyCollection baseProps = base.Properties;
                    baseProps.Add(new ConfigurationProperty(
                                      "userName",
                                      typeof (String),
                                      null,
                                      null,
                                      new StringValidator(1),
                                      ConfigurationPropertyOptions.IsRequired));
                    baseProps.Add(new ConfigurationProperty(
                                      "password",
                                      typeof (String),
                                      ""));
                    properties = baseProps;
                }
                return properties;
            }
        }
    
        protected override object CreateBehavior()
        {
            var creds = (ClientCredentials) base.CreateBehavior();
            creds.UserName.UserName = UserName;
            if (Password != null) creds.UserName.Password = Password;
            ApplyConfiguration(creds);
            return creds;
        }
    }
    

    After which you need to register this custom implementation using something like

    
      
        
          
        
      
    ...
    

提交回复
热议问题