是否可以在 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/