Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

c# - How can I add authorization header to the request in 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);

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simplest way is to add it on the client side:

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);
     }
}

and retrieve it on the server side:

string  auth = OperationContext.Current.IncomingMessageHeaders.
GetHeader<string>("Authorization", "http://mynamespace.com/v1");

I also suggest that you check these articles:

Authorization Header is missing in Http request using WCF

WCF Service with wsHttpBinding - Manipulating HTTP request headers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...