通过cookie发送信息也可能是一个选项,您可以尝试以下操作,
服务侧
创建一个实现
IDispatchMessageInspector
public class IdentityMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
var messageProperty = (HttpRequestMessageProperty)
OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
string cookie = messageProperty.Headers.Get("Set-Cookie");
if (cookie == null) // Check for another Message Header - SL applications
{
cookie = messageProperty.Headers.Get("Cookie");
}
if (cookie == null)
cookie = string.Empty;
//You can get the credentials from here, do something to them, on the service side
}
注意这一行
OperationContext.IncomingMessageProperties Property
,可用于获取消息的输入消息属性,根据链接的msdn链接,
使用此属性检查或修改服务操作中的请求消息或客户端代理中的答复消息的消息属性
,然后创建一个实现
IServiceBehvaior
,例如
公共类拦截器行为张力:行为张力,IServicebehavior,
您将需要实现接口,并修改
应用DispatchBehavior
方法如下
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
{
foreach (var endpoint in dispatcher.Endpoints)
{
endpoint.DispatchRuntime.MessageInspectors.Add(new IdentityMessageInspector());
}
}
}
,然后继续将其添加到web.config/app.config文件中。
<extensions>
<behaviorExtensions>
<add name="interceptorBehaviorExtension" type="test.InterceptorBehaviorExtension, test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
,然后包括行
<interceptorBehaviorExtension />
在行为元素标记中。
顾客
在客户端,您需要使用
IClientMessageInspector
并修改
public对象beforesendRequest(ref system.serviceModel.channels.message请求,
system.serviceModel.iclientchannel频道)
方法将凭据添加到客户端代码。
接下来,将此添加到实现
IEndpointBehavior
,
内部类拦截器行为拉伸:行为拉伸元素,IEndPointBehavior
并修改
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new CookieMessageInspector());
}
方法,然后将上述代码添加到WCF客户端代码中的端点行为列表中,
不过,我想您可以使用httpclient或webclient添加代码,并在连接到服务以提供凭据时使用该代码。
更新:
解决方案的关键是从这行中的原始HTTP消息获取头:
var messageProperty = (HttpRequestMessageProperty)OperationContext.Current
.IncomingMessageProperties[HttpRequestMessageProperty.Name];
这允许您这样访问授权头:
string authorization = message.Headers.Get("Authorization");
自从
OperationContext
可以从服务本身读取,可以直接从服务读取和解析授权数据。在基本身份验证的情况下,这包括用户名和密码。不需要消息检查器(尽管您需要额外的
UserNamePasswordValidator
在验证时忽略密码)。