Search code examples
c#azure-functionssystem.net

How to properly add HttpRequestHeaders using system.net.http library


I created a HttpRequestMessage with header using windows.web.http; library:

var request = base.CreateHttpRequestMessage();
        request.Headers.Add("SESSION", SessionId);
        return request;

and after sending SendRequestAsync(); , I am able to get the response successfully .

But in my case I need to use system.net.http; library, with same codes:

var request = base.CreateHttpRequestMessage();
        request.Headers.Add("SESSION", SessionId);
        return request;

but when I am calling the SendAsync(); , I am getting an UnAuthorized response. Does anyone knows what causing the issue?

var source = new CancellationTokenSource(timeout)
var response = await _client.SendAsync(request, source.Token)
                    .ConfigureAwait(false);

NOTE: I tried manually setting same valid SessionId for both , on windows.web.http its Okay, but on system.net.http its unauthorized.

How I initialize my HttpClient:

private HttpClientHandler handler;
handler = new HttpClientHandler();

private HttpClient _client;
_client = new HttpClient(handler)

Reference Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http?view=netframework-4.7.2
https://learn.microsoft.com/en-us/uwp/api/windows.web.http

Requests Header format:
windows.web.http: enter image description here system.net.http: enter image description here

Thanks.


Solution

  • After debugging the request using Fiddler, I found out that the cookie of my request is null, so I fixed this by adding the cookie instead of adding the header.

    CookieContainer.Add(request.RequestUri, new Cookie("SESSION", SessionId));