Search code examples
c#httprequestconsole-application.net-7.0

HttpClient.SendAsync has no headers


I have a problem with HttpClient.SendAsync, I have tried to send POST request with Authorization header, but when it was sent it has no that headers data, here is my send request codes:

static readonly HttpClient Client = new HttpClient();
        string data = "{\"key\":\"value\"}";
        long responseCode = -1;
        string stringContent = string.Empty;
        string authorizationToken = "secret";
        using (var webRequest = new HttpRequestMessage(HttpMethod.Post, url))
        {
            webRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
            webRequest.Content = new StringContent(data, Encoding.UTF8, "application/json");
            try
            {
                using var resp = await Client.SendAsync(webRequest);
                {
                    responseCode = (long)resp.StatusCode;
                    stringContent = await resp.Content.ReadAsStringAsync();
                }
                Debug.WriteLine($"[Info] POST Result {id} {responseCode} {stringContent}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[Error] Cannot POST: {url} {ex.Message}");
            }
        }

Codes for the web-service side

<?php
print_r(getallheaders());

When I use other clients (such as Insomnia) its result have headers as expected

Array
(
    [Host] => localhost
    [User-Agent] => insomnia/2022.6.0
    [Content-Type] => application/x-www-form-urlencoded
    [Authorization] => Bearer hello
    [Accept] => */*
)

But for the HttpClent it only shows

Array
(
    [Host] => localhost
)

It is console application project.


Solution

  • and found the issues, seems like it is a redirection issues, data missing when redirected.

    From HttpClientHandler.AllowAutoRedirect docs:

    The Authorization header is cleared on auto-redirects and the handler automatically tries to re-authenticate to the redirected location. No other headers are cleared. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection. Instead, the application must implement and register a custom authentication module.

    Use the https address so there is no redirect or try implementing something like this.