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

耗尽温柔 提交于 2019-12-11 04:12:55

问题


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://docs.microsoft.com/en-us/dotnet/api/system.net.http?view=netframework-4.7.2
https://docs.microsoft.com/en-us/uwp/api/windows.web.http

Requests Header format:
windows.web.http: system.net.http:

Thanks.


回答1:


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));



回答2:


One disadvantage of system.net.http is that doesn't cache requests. Server that doesn't send Cache-Control can be potential problem.



来源:https://stackoverflow.com/questions/53717977/how-to-properly-add-httprequestheaders-using-system-net-http-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!