gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:51:54 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com