簡體   English   中英

SOAP調用中的授權標頭

[英]Authorization Header in SOAP call

我將WSDL導入到我的C#.NET項目中。 之后我不得不生成訪問令牌,現在我必須在調用SOAP服務時通過授權頭使用此令牌。 這有什么簡單的方法嗎?

MemberAccountPortClient clientTransaction = new MemberAccountPortClient ("SERVICE");
SearchTransactionResponseType res = clientTransaction.searchTransaction (OBJECT_1, OBJECT_2);

在這種情況下如何添加授權標頭?

您可以創建IClientMessageInspector / IEndpointBehavior來設置此值,如下所示:(是的,這段代碼很詳細,但這就是WCF的工作方式;)

using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

public class AuthorizationHeaderMessageInspector : IClientMessageInspector, IEndpointBehavior
{
    object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        HttpRequestMessageProperty prop;
        Object obj;
        if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
        {
            prop = (HttpRequestMessageProperty)obj; // throws a cast exception if invalid type
        }
        else
        {
            prop = new HttpRequestMessageProperty();
            request.Properties.Add(HttpRequestMessageProperty.Name, prop);
        }
        prop.Headers[HttpRequestHeader.Authorization] = "your authorization value here";

        return null;
    }

    void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
    {
    }

    void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(this);
    }

    void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
    {
    }
}

然后,在創建客戶端時,添加消息檢查器,如下所示:

MemberAccountPortClient clientTransaction = new MemberAccountPortClient ("SERVICE");
clientTransaction.Endpoint.Behaviors.Add(new AuthorizationHeaderMessageInspector());
SearchTransactionResponseType res = clientTransaction.searchTransaction (OBJECT_1, OBJECT_2);

我相信WCF也有一種方法可以使用配置來應用IEndpointBehavior ,但我通常會直接編寫這些類型的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM