c# - 在 App.config 中设置 WCF ClientCredentials

标签 c# .net vb.net wcf configuration

是否可以在 App.config 中为 WCF 设置客户端凭据?

我想避免这样做:

Using svc As New MyServiceClient
  svc.ClientCredentials.UserName.UserName = "login"
  svc.ClientCredentials.UserName.Password = "pw"

  ...
End Using

登录名和密码应该是配置的一部分。

最佳答案

扩展 Ladislav Mrnka 的回答,您可能会发现此实现很有用:

public class UserNameClientCredentials : ClientCredentialsElement
{
    private ConfigurationPropertyCollection properties;

    public override Type BehaviorType
    {
        get { return typeof (ClientCredentials); }
    }

    /// <summary>
    /// Username (required)
    /// </summary>
    public string UserName
    {
        get { return (string) base["userName"]; }
        set { base["userName"] = value; }
    }

    /// <summary>
    /// Password (optional)
    /// </summary>
    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;
    }
}

之后您需要使用类似的方式注册此自定义实现

<system.serviceModel>
  <extensions>
    <behaviorExtensions>
      <add name="UserNameClientCredentials" type="MyNamespace.UserNameClientCredentials, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </behaviorExtensions>
  </extensions>
...

关于c# - 在 App.config 中设置 WCF ClientCredentials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3725294/

相关文章:

javascript - AJAX Post 请求发送重复请求

c# - Linq 查询 XML 以选择子节点的多个元素

c# - 如何重叠两个控件

c# - C#.net 中的 XML 数据库

c# - 确定将要在@RenderBody() 中呈现的 View

.net - Visual Studio 2008 调试器不报告一些常见错误

c# - 在 VB.NET 或 C# 中,父类的子类和基类的派生有什么区别?

c# - PrincipalPermission 与授权属性?

javascript - 在服务器端获取隐藏字段的空值

c# - 在 C# 中添加 SQL 参数