Search code examples
c#http-headersreddit

Compile error while initializing HttpRequest headers


I am trying to initialize an HttpClient based on some Python code.

I am getting a compiler error when trying to create a custom header for the 'data' header in the python code:

cannot convert from 'System.Collections.Generic.Dictionary<string, string>' to 'System.Collections.Generic.IEnumerable<string?>

Same for a custom header for the "headers" header:

cannot convert from 'System.Collections.Generic.KeyValuePair<string, string>' to 'System.Collections.Generic.IEnumerable<string?>

C# code

Dictionary<string, string> data = new Dictionary<string, string>()
{
    {"grant_type", "password" },
    {"username", Username },
    {"password", Password }
};
tokenApiClient.DefaultRequestHeaders.Add("data", data); Compiler Error: cannot convert from 'System.Collections.Generic.Dictionary<string, string>' to 'System.Collections.Generic.IEnumerable<string?>

KeyValuePair<string, string> headers = new KeyValuePair<string, string>("User-Agent", "Post analysis for neural network text generation.");
tokenApiClient.DefaultRequestHeaders.Add("headers", headers); // Compile Error: cannot convert from 'System.Collections.Generic.KeyValuePair<string, string>' to 'System.Collections.Generic.IEnumerable<string?>'

Python code

data = {
    'grant_type': 'password',
        'username': '<USERNAME>',
        'password': '<PASSWORD>'}

headers = { 'User-Agent': 'MyBot/0.0.1'}

res = requests.post('https://www.reddit.com/api/v1/access_token',
        auth=auth, data=data, headers=headers)

How can I Initialize it so it would act like the Python code?


Solution

  • Doc: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.headers.httpheaders.add?view=net-5.0

    The Add method signature accepts (string, string) or (string, IEnumerable<string>).

    Looks like you'll have to loop through the dictionary and call Add per dictionary item.

    You can also create some convenient extension methods, for example:

    public static class MyHttpExtensions 
    {
        public static void Add(this HttpHeaders header, IDictionary<string, string> dictTable) 
        {
            foreach (var item in dictTable) 
            {
                header.Add(item.Key, item.Value);
            }
        }
    }