Search code examples
c#apihttp-headersapi-key

How do I set the api key in System.Net.WebClient


What would be the best way for me to set the api key value when deserealizing json from a url. The code I am using is below but I don't know how to state the api key

using (var webClient = new System.Net.WebClient())
    {
        var myTable = webClient.DownloadString(url);
        var deserealizedTable = JsonConvert.DeserializeObject<MyClass>(myTable);
    }

The providers of the key said I should modify my client to use a header-field "Authentication-Token" with the token that was provided as the value.


Solution

  • You can add headers to requests by adding to the Headers property of WebClient.

    using (var webClient = new System.Net.WebClient())
    {
        webClient.Headers.Add("Authentication-Token", apiKey);
        var myTable = webClient.DownloadString(url);
        ...
    }