如何为每个WCF调用添加自定义HTTP标头?

mrt*_*ndi 157 wcf

我有一个托管在Windows服务中的WCF服务.使用此服务的客户端每次调用服务方法时都必须传递一个标识符(因为该标识符对于被调用的方法应该做什么很重要).我认为以某种方式将此标识符放入WCF头信息是个好主意.

如果是个好主意,我该如何自动将标识符添加到标题信息中.换句话说,每当用户调用WCF方法时,标识符必须自动添加到标头中.

更新: 使用WCF服务的客户端是Windows应用程序和Windows Mobile应用程序(使用Compact Framework).

Mar*_*ood 181

这样做的好处是它适用于每次通话.

创建一个实现IClientMessageInspector的类.在BeforeSendRequest方法中,将自定义标头添加到外发邮件中.它可能看起来像这样:

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,  System.ServiceModel.IClientChannel channel)
{
    HttpRequestMessageProperty httpRequestMessage;
    object httpRequestMessageObject;
    if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
    {
        httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
        if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
        {
            httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
        }
    }
    else
    {
        httpRequestMessage = new HttpRequestMessageProperty();
        httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个端点行为,将消息检查器应用于客户端运行时.您可以通过属性或使用行为扩展元素的配置来应用行为.

以下是如何将HTTP用户代理标头添加到所有请求消息的一个很好的示例.我在一些客户中使用它.您也可以通过实现IDispatchMessageInspector在服务端执行相同的操作.

这是你的想法吗?

更新: 我发现了紧凑框架支持的WCF功能列表.我相信消息检查员被归类为"渠道可扩展性",根据这篇文章,受到紧凑框架的支持.

  • +1`OutgoingMessageProperties`是您访问HTTP标头所需要的 - 而不是作为SOAP标头的`OutgoingMessageHeaders`. (10认同)
  • 这只允许一个硬编码的用户代理,根据给定的例子,它在web.config中是硬编码的! (3认同)
  • @Mark,这是一个非常好的答案。谢谢。我已经在 net.tcp 上尝试过这个,但我直接使用了 Headers 集合(Http Headers 不起作用)。我在 ServiceHost AfterReceiveRequest 事件中得到了一个带有我的令牌(名称)的标头,但不是值(甚至似乎没有值的属性?)。有什么我想念的吗?我本来希望有一个名称/值对,因为当我创建它要求我提供的标头时: request.Headers.Add(MessageHeader.CreateHeader(name, ns, value)); (2认同)

Agi*_*Jon 79

您可以使用以下命令将其添加到呼叫

using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
    MessageHeader<string> header = new MessageHeader<string>("secret message");
    var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
    OperationContext.Current.OutgoingMessageHeaders.Add(untyped);

    // now make the WCF call within this using block
}
Run Code Online (Sandbox Code Playgroud)

然后,服务器端你使用以下方法获取它:

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的代码片段.但是有了这个,我每次要调用方法时都要添加标题.我想让这个过程透明化.我的意思是实现一次,每次用户创建服务客户端并使用方法时,客户头自动添加到消息中. (5认同)
  • 需要注意的是,如果您在调用过程中进行任何异步处理,这是有问题的,因为“ OperationContextScope”(和“ OperationContext”)是“ ThreadStatic”-** Mark Good **的答案可以不依赖`ThreadStatic`项目。 (2认同)
  • 这不会添加 HTTP 标头!它将标头添加到 SOAP 信封中。 (2认同)

Nim*_*van 32

如果您只想为服务的所有请求添加相同的标头,您可以不使用任何编码!
只需在客户端配置文件的端点节点下添加头节点和必需的头

<client>  
  <endpoint address="http://localhost/..." >  
    <headers>  
      <HeaderName>Value</HeaderName>  
    </headers>   
 </endpoint>  
Run Code Online (Sandbox Code Playgroud)

  • 这些是SOAP标头(*ala [`MessageHeader`](http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messageheader.aspx)*) - 不是HTTP标头. (15认同)

br3*_*3nt 19

如果您想以面向对象的方式向每个 WCF 调用添加自定义 HTTP 标头,那么无需再犹豫了。

正如 Mark Good 和 paulwhit 的回答一样,我们需要子类化IClientMessageInspector以将自定义 HTTP 标头注入到 WCF 请求中。但是,让我们通过接受包含我们要添加的标头的字典来使检查器更加通用:

public class HttpHeaderMessageInspector : IClientMessageInspector
{
    private Dictionary<string, string> Headers;

    public HttpHeaderMessageInspector(Dictionary<string, string> headers)
    {
        Headers = headers;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        // ensure the request header collection exists
        if (request.Properties.Count == 0 || request.Properties[HttpRequestMessageProperty.Name] == null)
        {
            request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
        }

        // get the request header collection from the request
        var HeadersCollection = ((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers;

        // add our headers
        foreach (var header in Headers) HeadersCollection[header.Key] = header.Value;

        return null;
    }

    // ... other unused interface methods removed for brevity ...
}
Run Code Online (Sandbox Code Playgroud)

正如 Mark Good 和 paulwhit 的回答一样,我们需要子类化IEndpointBehavior以将其注入HttpHeaderMessageInspector到 WCF 客户端中。

public class AddHttpHeaderMessageEndpointBehavior : IEndpointBehavior
{
    private IClientMessageInspector HttpHeaderMessageInspector;

    public AddHttpHeaderMessageEndpointBehavior(Dictionary<string, string> headers)
    {
        HttpHeaderMessageInspector = new HttpHeaderMessageInspector(headers);
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(HttpHeaderMessageInspector);
    }

    // ... other unused interface methods removed for brevity ...
}
Run Code Online (Sandbox Code Playgroud)

完成面向对象方法所需的最后一部分是创建 WCF 自动生成的客户端的子类(我使用 Microsoft 的WCF Web 服务参考指南来生成 WCF 客户端)。

就我而言,我需要将 API 密钥附加到x-api-keyHTML 标头。

子类执行以下操作:

  • 使用所需参数调用基类的构造函数(在我的例子中,EndpointConfiguration生成了一个枚举以传递给构造函数 - 也许您的实现不会有这个)
  • 定义应附加到每个请求的标头
  • 依附于AddHttpHeaderMessageEndpointBehavior客户的Endpoint行为
public class Client : MySoapClient
{
    public Client(string apiKey) : base(EndpointConfiguration.SomeConfiguration)
    {
        var headers = new Dictionary<string, string>
        {
            ["x-api-key"] = apiKey
        };

        var behaviour = new AddHttpHeaderMessageEndpointBehavior(headers);
        Endpoint.EndpointBehaviors.Add(behaviour);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,使用您的客户端!

var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var client = new Client (apiKey);
var result = client.SomeRequest()
Run Code Online (Sandbox Code Playgroud)

生成的 HTTP 请求应包含您的 HTTP 标头,如下所示:

POST http://localhost:8888/api/soap HTTP/1.1
Cache-Control: no-cache, max-age=0
Connection: Keep-Alive
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
x-api-key: XXXXXXXXXXXXXXXXXXXXXXXXX
SOAPAction: "http://localhost:8888/api/ISoapService/SomeRequest"
Content-Length: 144
Host: localhost:8888

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <SomeRequestxmlns="http://localhost:8888/api/"/>
  </s:Body>
</s:Envelope>
Run Code Online (Sandbox Code Playgroud)


Sli*_*SFT 14

这是另一个有用的解决方案,使用ChannelFactory作为代理手动将自定义HTTP标头添加到客户端WCF请求.这必须针对每个请求进行,但如果您只是需要对代理进行单元测试以准备非.NET平台,那么就足够了.

// create channel factory / proxy ...
using (OperationContextScope scope = new OperationContextScope(proxy))
{
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty()
    {
        Headers = 
        { 
            { "MyCustomHeader", Environment.UserName },
            { HttpRequestHeader.UserAgent, "My Custom Agent"}
        }
    };    
    // perform proxy operations... 
}
Run Code Online (Sandbox Code Playgroud)

  • 我尝试了其他 4 个类似的建议,这是唯一对我有用的建议。 (2认同)

Ωme*_*Man 10

这类似于NimsDotNet的答案,但显示了如何以编程方式执行此操作.

只需将标题添加到绑定即可

var cl = new MyServiceClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( 
      AddressHeader.CreateAddressHeader("ClientIdentification",  // Header Name
                                         string.Empty,           // Namespace
                                         "JabberwockyClient"));  // Header Value

cl.Endpoint.Address = eab.ToEndpointAddress();
Run Code Online (Sandbox Code Playgroud)

  • 这会向 SOAP 信封添加标头,而不是 HTTP 标头 (3认同)
  • 知道了 !System.ServiceModel.Channels.MessageHeaders headers = operationContext.RequestContext.RequestMessage.Headers; int headerIndex = headers.FindHeader("ClientIdentification", string.Empty); var requestName = (headerIndex &lt; 0) ? “未知”:headers.GetHeader&lt;string&gt;(headerIndex); (2认同)

pau*_*hit 7

这对我有用,改编自《Adding HTTP Headers to WCF Calls》

// Message inspector used to add the User-Agent HTTP Header to the WCF calls for Server
public class AddUserAgentClientMessageInspector : IClientMessageInspector
{
    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
    {
        HttpRequestMessageProperty property = new HttpRequestMessageProperty();

        var userAgent = "MyUserAgent/1.0.0.0";

        if (request.Properties.Count == 0 || request.Properties[HttpRequestMessageProperty.Name] == null)
        {
            var property = new HttpRequestMessageProperty();
            property.Headers["User-Agent"] = userAgent;
            request.Properties.Add(HttpRequestMessageProperty.Name, property);
        }
        else
        {
            ((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers["User-Agent"] = userAgent;
        }
        return null;
    }

    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
    }
}

// Endpoint behavior used to add the User-Agent HTTP Header to WCF calls for Server
public class AddUserAgentEndpointBehavior : IEndpointBehavior
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new AddUserAgentClientMessageInspector());
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

声明这些类后,您可以将新行为添加到 WCF 客户端,如下所示:

client.Endpoint.Behaviors.Add(new AddUserAgentEndpointBehavior());
Run Code Online (Sandbox Code Playgroud)


小智 5

var endpoint = new EndpointAddress(new Uri(RemoteAddress),
               new[] { AddressHeader.CreateAddressHeader(
                       "APIKey", 
                       "",
                       "bda11d91-7ade-4da1-855d-24adfe39d174") 
                     });
Run Code Online (Sandbox Code Playgroud)

  • 这是SOAP消息头,而不是HTTP头. (10认同)

Tar*_*ran 5

这对我有用

TestService.ReconstitutionClient _serv = new TestService.TestClient();

using (OperationContextScope contextScope = new OperationContextScope(_serv.InnerChannel))
{
   HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();

   requestMessage.Headers["apiKey"] = ConfigurationManager.AppSettings["apikey"]; 
   OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = 
      requestMessage;
   _serv.Method(Testarg);
}
Run Code Online (Sandbox Code Playgroud)