当前,我正在使用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.GetCookies()方法访问CookieContainer,以便可以从HttpResponseMessage复制各种Cookie,例如会话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标头中。
答案 0 :(得分: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;
答案 1 :(得分:0)
如果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; }
答案 2 :(得分:-2)
$.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) {}
});