使用 ChannelFactory创建具有不同凭证的通道
我使用 ChannelFactory
类型在 WsHttpBinding
WCF Web 服务中创建通道,并且该服务使用用户名/密码组合进行身份验证。虽然我使用自定义验证器进行身份验证,但我很难创建具有不同凭据的通道。
考虑到创建 ChannelFactory
的开销,我尝试缓存它的单个实例,并在应用程序的生命周期内共享它以创建多个通道。不幸的是,凭证似乎直接与工厂绑定,并且在创建通道后无法更改。
换句话说,如果我尝试这样做:
factory.Credentials.UserName.UserName = "Bob";
factory.Credentials.UserName.Password = "password";
var channel1 = factory.CreateChannel();
factory.Credentials.UserName.UserName = "Alice"; // exception here
factory.Credentials.UserName.Password = "password";
var channel1 = factory.CreateChannel();
我会收到一个异常,告诉我 UserName
属性现在是只读的。
是否可以在这里实现任何类型的缓存,或者我本质上必须为每个用户名缓存一个 ChannelFactory
实例?
I am using the ChannelFactory<T>
type to create channels into a WsHttpBinding
WCF web service, and the service uses a username/password combination to authenticate. While I have the authentication working using my custom validator, I am having difficulty creating channels with differing credentials.
Given the overhead of creating ChannelFactory<T>
, I'm trying to cache a single instance of it and share it for the creation of multiple channels over the lifetime of my application. Unfortunately, it seems like the credentials are directly tied to the factory and cannot be changed after a channel has been created.
In other words, if I try this:
factory.Credentials.UserName.UserName = "Bob";
factory.Credentials.UserName.Password = "password";
var channel1 = factory.CreateChannel();
factory.Credentials.UserName.UserName = "Alice"; // exception here
factory.Credentials.UserName.Password = "password";
var channel1 = factory.CreateChannel();
I get an exception telling me that the UserName
property is now read-only.
Is it possible to implement any sort of caching here, or am I essentially going to have to cache an instance of ChannelFactory
for every username?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 MSDN 上的记录,这不可能直接实现(
Credentials
在ChannelFactory
的Open
时变为只读)...如果你真的想这样做,你需要欺骗ChannelFactory
像这样:另一个选择似乎是在尝试更改
Credentials
之前Close()
ChannelFactory
。否则,只需坚持为不同的凭证缓存不同的 ChannelFactories...
As documented on MSDN this is not directly possible (
Credentials
become readonly uponOpen
of theChannelFactory
)... if you really want to do this you will need to trick theChannelFactory
like this:Another option seems to be to
Close()
theChannelFactory
before trying to change theCredentials
.Otherwise just stick with caching different ChannelFactories for different Credentials...
您需要创建一个新的通道工厂。当工厂创建第一个通道时,它的属性变为只读(有些属性会抛出异常,如您所见;另一些属性更糟,您更改但没有任何反应,例如,如果您更改传递给的绑定元素中的某些属性CF 构造函数)。
You'll need to create a new channel factory. When the factory creates the first channel, its properties become read-only (some throw the exception as you see; some others are worse in which you change but nothing happens, for example if you change some property in a binding element which you passed to the CF constructor).