我正在开发一个 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:
使用 WCF 的 Http 请求中缺少授权标头一个>
使用 wsHttpBinding 的 WCF 服务 - 操作 HTTP 请求标头
这篇关于如何向 WCF 中的请求添加授权标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!