Search code examples
c#wcf

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


A web service that I'm trying to consume requires that I add x-api-key to the HTTP header of the request. Is it possible to add this new header to the request using the web.config? I've tried to add the header element to the endpoint like the example below, but keep getting 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>

Solution

  • Couldn't find a way to do it through web.config, so I developed a solution based on 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);
    }