我真的需要知道如何在不向所有合同添加额外参数的情况下将令牌传递给 WCF 服务,例如数字之类的一些值,以便我以后可以在我的服务中使用它。
问问题
2496 次
2 回答
2
使用自定义标题解决了这个问题。
您可以像这样为您的客户分配一个自定义标头:
IContextChannel contextChannel = (IContextChannel)myServiceProxy;
using (OperationContextScope scope = new OperationContextScope(contextChannel))
{
MessageHeader header = MessageHeader.CreateHeader("PlayerId", "", _playerId);
OperationContext.Current.OutgoingMessageHeaders.Add(header);
act(service);
}
在服务端,您可以获得此值:
private long ExtractPlayerIdFromHeader()
{
try
{
var opContext = OperationContext.Current;
var requestContext = opContext.RequestContext;
var headers = requestContext.RequestMessage.Headers;
int headerIndex = headers.FindHeader("PlayerId", "");
long playerId = headers.GetHeader<long>(headerIndex);
return playerId;
}
catch (Exception ex)
{
this.Log.Error("Exception thrown when extracting the player id from the header", ex);
throw;
}
}
另请参阅此问题,了解如何通过配置文件设置自定义标头。
于 2013-04-07T22:44:46.757 回答