添加 x-api-key 以使用 web.config 请求 HTTP header

Add x-api-key to request HTTP header using web.config

我尝试使用的 Web 服务要求我将 x-api-key 添加到请求的 HTTP header。 是否可以使用 web.config 将这个新的 header 添加到请求中?我尝试将 header 元素添加到端点,如下例所示,但一直收到 403-Forbidden:

<endpoint address="webserviceurl"
    behaviorConfiguration="myBehavior" binding="customBinding"
    bindingConfiguration="myBinding" contract="myContract"
    name="serviceName">
    <headers>
      <x-api-key xmlns="webserviceurl">"key"</x-api-key>
    </headers>
</endpoint>

找不到通过web.config的方法,所以我开发了一个基于this answer的解决方案:

WSClient client = new WSClient("endpointName");

using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
    WebOperationContext.Current.OutgoingRequest.Headers.Add("X-API-KEY", "key");
    WSRequest req = new WSRequest();
    WSResponse resp = client.WSMethod(req);
}