Search code examples
c#nethereum

How do I add a header to every Nethereum RPC request?


I would like to add a header (namely x-api-key) to each RPC request fired off by the Web3 class. How do I do this?

I have tried using AuthenticationHeaderValue as a constructor parameter but from what I can tell either my implementation is incorrect (new AuthenticationHeaderValue("x-api-key", "(api key here)")) or AuthenticationHeaderValue will not work as this is not a standard schema.


Solution

  • I was able to add headers to my requests by instantiating Web3 with an RpcClient instance instead of the simpler constructor. Doing so, I injected my own HttpClient with default headers already set.

    httpClient
            .DefaultRequestHeaders
            .Add("x-api-key", configuration.GetRequiredSection("Web3:APIKey").Value ?? throw new Exception("Web3 API Key not set in configuration"));
        
    var rpcClient = new RpcClient(new Uri(configuration.GetRequiredSection("Web3:RPCUrl").Value ??
                                              throw new Exception("RPC URL has not been set in configuration")),
            httpClient, log: _logger);
        
    _web3 = new Web3(rpcClient);