SOAP调用中的授权标头

时间:2017-01-26 16:52:58

标签: c# .net soap .net-4.5

我将一个WSDL导入到我的C#.NET项目中。之后我不得不生成访问令牌,现在我必须在调用SOAP服务时通过授权头使用此令牌。对此有什么简单的方法吗?

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

在这种情况下如何添加授权标头?

1 个答案:

答案 0 :(得分:0)

您可以创建IClientMessageInspector / IEndpointBehavior来设置此值,如下所示:(是的,此代码详细,但这就是WCF的工作方式;)

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使用配置,但我通常直接代码来处理这些类型的事情。