我该如何授权头添加到WCF的要求? [英] How can I add authorization header to the request in WCF?
问题描述
我工作的一个Windows窗体应用程序,有需要调用WCF服务。我需要一个头(授权 - 自定义)之前添加它发送到服务请求。我有一个自定义类检查为好。我尝试以下,但该服务不叫,不知何故,它返回一个例外。
I'm working on a Windows Form application and there's a WCF service that needs to be called. I need to add a header (authorization - custom) to the request before it's sent to the service. I have a custom inspector class as well. I tried the following but the service is not called, somehow, and it returns an exception.
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
MessageHeader header = MessageHeader.CreateHeader("Authorization", "", "Basic Y19udGk6Q29udGlfQjNTVA==");
OperationContext.Current.OutgoingMessageHeaders.Add(header);
HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers.Add("Authorization", "Basic Y19udGk6Q29udGlfQjNTVA==");
httpRequestProperty.Headers.Add(HttpRequestHeader.UserAgent, "Continental");
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
sentMessages.Add(request.ToString());
return null;
}
我也试过像这样的简单的方法:
I also tried simplest way like this one:
MessageHeader header = MessageHeader.CreateHeader("Authorization", "", "Basic Y19udGk6Q29udGlfQjNTVA==");
request.Headers.Add(header);
但它是相同的,授权头被添加,但它没有达到的服务,我怎么能知道是由服务接收什么头?我用SOAP UI和服务响应很好,当我在请求中手动添加这样的标题(运行前)。
but it's the same, authorization header is added but it does not reach the service, how can I know what header is received by the service? I used SOAP UI and service responds well when I add such a header manually in the request (before running).
推荐答案
最简单的方法是将添加在客户端
using (MyServ.ServiceClient proxy = new MyServ.ServiceClient())
{
using (new System.ServiceModel.OperationContextScope(proxy.InnerChannel))
{
MessageHeader head = MessageHeader.CreateHeader("Authorization", "http://yournamespace.com/v1", data);
OperationContext.Current.OutgoingMessageHeaders.Add(head);
}
}
和获取它在服务器端
string auth = OperationContext.Current.IncomingMessageHeaders.
GetHeader<string>("Authorization", "http://mynamespace.com/v1");
我也建议你检查这些文章:
I also suggest that you check these articles:
<一个href=\"http://stackoverflow.com/questions/4080986/authorization-header-is-missing-in-http-request-using-wcf\">Authorization头是使用WCF 缺少Http请求
<一个href=\"http://stackoverflow.com/questions/9111361/wcf-service-with-wshttpbinding-manipulating-http-request-headers\">WCF用的wsHttpBinding服务 - 操纵HTTP请求头
这篇关于我该如何授权头添加到WCF的要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!