我要使用的Web服务要求将x-api-key添加到请求的HTTP标头中。是否可以使用web.config将此新标头添加到请求中?我尝试将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);
}