如何使用system.net.http库正确添加HttpRequestHeaders [英] How to properly add HttpRequestHeaders using system.net.http library

查看:784
本文介绍了如何使用system.net.http库正确添加HttpRequestHeaders的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 windows.web.http; 库创建了带有标头的HttpRequestMessage:

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

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

,并在发送SendRequestAsync()之后; ,我就能成功获得响应.

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

但是对于我来说,我需要使用具有相同代码的 system.net.http; 库:

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;

但是当我调用SendAsync()时; ,我收到未经授权的回复. 有人知道导致问题的原因吗?

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

注意::我尝试在 windows.web.http 上为它们手动设置相同的有效 SessionId ,但在 system.net.http 未经授权.

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

我如何初始化HttpClient:

How I initialize my HttpClient:

private HttpClientHandler handler;
handler = new HttpClientHandler();

private HttpClient _client;
_client = new HttpClient(handler)

参考链接: https://docs.microsoft.com/zh-cn/dotnet/api/system.net.http?view=netframework-4.7.2
https://docs.microsoft.com/en-us/uwp/api/windows.web.http

请求标头格式:
windows.web.http: system.net.http:

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

谢谢.

推荐答案

使用Fiddler调试请求后,我发现请求的cookie为空,因此我通过添加cookie而不是添加标题来解决此问题.

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

这篇关于如何使用system.net.http库正确添加HttpRequestHeaders的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆