6

目前我正在开发一个使用 ASP.NET Core 2 编写的项目,并且正在尝试从第三方网站获取 JSON 文件。问题是该网站需要一些 cookie 才能从中检索数据。我在我的 Startup.cs 文件中实现了一个类型化的 HttpClient,如下所示:

    services.AddHttpClient<IMyClient, MyClient>().ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
            UseCookies = true,
            UseDefaultCredentials = true,
            CookieContainer = new CookieContainer()
        };
    });

有什么方法可以访问 CookieContainer 以使用 CookieContainer.GetCookies() 方法,以便我可以从 HttpResponseMessage 复制各种 cookie,如 Session Cookie 和一些验证令牌?

对不起,如果我做错了什么,这是我的第一篇文章。

编辑

通过在请求管道中添加 HttpMessageHandler 使其工作

services.AddHttpClient<IMyHttpClient, MyHttpClient>()
                    .AddHttpMessageHandler<MyMessageHandler>();

并编辑HttpMessageHandler中的http头信息

public class MyMessageHandler : DelegatingHandler
{
    private readonly CookieContainer _cookies;

    public MyMessageHandler()
    {
        _cookies = new CookieContainer();
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken cancellationToken)
    {
        try
        {
            if (_cookies.Count == 0 && message.RequestUri.Host.Contains("example.com"))
            {
                // Simulate the Request
                var getCookieMesssage = new HttpRequestMessage()
                {
                    RequestUri = new Uri("http://www.example.com/"),
                    Content = message.Content,
                    Method = HttpMethod.Get,
                };

                // Simulate User Agent
                foreach(var agent in message.Headers.UserAgent)
                {
                    getCookieMesssage.Headers.UserAgent.Add(agent);
                }

                var testResponse = await base.SendAsync(getCookieMesssage, cancellationToken);

                if (testResponse.Headers.TryGetValues("Set-Cookie", out var newCookies))
                {
                    foreach (var item in SetCookieHeaderValue.ParseList(newCookies.ToList()))
                    {
                        var uri = new Uri(message.RequestUri, item.Path.Value);

                        // Add parsed cookies to CookieContainer
                        _cookies.Add(uri, new Cookie(item.Name.Value, item.Value.Value, item.Path.Value));
                    }
                }
                // Add parsed cookies to the header of the HttpRequestMessage
                message.Headers.Add("Cookie", _cookies.GetCookieHeader(message.RequestUri));
            }
            // get response
            var response = await base.SendAsync(message, cancellationToken).ConfigureAwait(false);

            return response;
        }catch(Exception ex)
        {
            throw ex;
        }

    }

}

此方法从 Set-Cookie 标头中获取所有 cookie,并将其添加到请求的 Cookie 标头中。

4

3 回答 3

1

如果MyClient是自定义实现,HttpClient您可以重载构造函数以存储对HttpClientHandler

public MyClient(HttpMessageHandler handler) 
       : base(handler)
{
    Handler = handler;
}

public MyClient(HttpMessageHandler handler, bool disposeHandler) 
       : base(handler, disposeHandler )
    Handler = handler;
)

public HttpMessageHandler Handler { get; }
于 2018-09-17T15:12:21.893 回答
1

您编辑的答案尚不清楚,因此我在此处对其进行了总结。此外,不需要显式设置HttpClientHandler.UseCookies = true或拥有CookieContainer.

要从调用中获取 cookie,您可以简单地读取"Set-Cookie"响应标头:

HttpResponseMessage response = await httpClient.GetAsync(uri);
IEnumerable<string> cookies = response.Headers.SingleOrDefault(header => header.Key == "Set-Cookie")?.Value;
于 2020-02-21T20:54:20.350 回答
-3
$.ajax({
            url: "https://localhost:44330/api/Records",
            type: 'POST',
            contentType:"application/json; charset=utf-8",
               dataType:"json",
            data: JSON.stringify(formdata),
            // Fetch the stored token from localStorage and set in the header
           headers: {"Authorization":'Bearer '+data.data.token},
            success: function(datas) {}
          });
于 2020-11-12T12:11:42.053 回答