我正在尝试使用 Web apiHttpClient
向需要以标识帐户的 HTTP cookie 的形式登录的端点发布帖子(这只是#ifdef
发布版本中删除的内容)。
如何将 cookie 添加到HttpRequestMessage
?
我正在尝试使用 Web apiHttpClient
向需要以标识帐户的 HTTP cookie 的形式登录的端点发布帖子(这只是#ifdef
发布版本中删除的内容)。
如何将 cookie 添加到HttpRequestMessage
?
以下是为请求设置自定义 cookie 值的方法:
var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("foo", "bar"),
new KeyValuePair<string, string>("baz", "bazinga"),
});
cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
var result = await client.PostAsync("/test", content);
result.EnsureSuccessStatusCode();
}
在大多数情况下,接受的答案是正确的方法。但是,在某些情况下,您需要手动设置 cookie 标头。通常,如果您设置“Cookie”标头,它会被忽略,但这是因为HttpClientHandler
默认使用其CookieContainer
属性来存储 cookie。如果您禁用它,那么通过设置UseCookies
您false
可以手动设置 cookie 标头,它们将出现在请求中,例如
var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var message = new HttpRequestMessage(HttpMethod.Get, "/test");
message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
var result = await client.SendAsync(message);
result.EnsureSuccessStatusCode();
}
在这个问题上花了几个小时后,上面的答案都没有帮助我,所以我找到了一个非常有用的工具。
首先,我使用 Telerik 的 Fiddler 4 详细研究了我的 Web Requests
其次,我遇到了 Fiddler 这个有用的插件:
https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode
它只会为您生成 C# 代码。一个例子是:
var uriBuilder = new UriBuilder("test.php", "test");
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());
httpRequestMessage.Headers.Add("Host", "test.com");
httpRequestMessage.Headers.Add("Connection", "keep-alive");
// httpRequestMessage.Headers.Add("Content-Length", "138");
httpRequestMessage.Headers.Add("Pragma", "no-cache");
httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
httpRequestMessage.Headers.Add("Origin", "test.com");
httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
// httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");
var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
var httpContent = httpResponseMessage.Content;
string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
请注意,我必须注释掉两行,因为这个插件还不完全完美,但它仍然完成了工作。
免责声明:无论如何,我都没有得到 Telerik 或插件作者的关联或认可。
对我来说,简单的解决方案可以在HttpRequestMessage对象中设置 cookie。
protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");
return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}
我有一个类似的问题,对于我的 AspNetCore 3.1 应用程序,这个问题的其他答案不起作用。我发现在我的配置中配置一个命名的 HttpClientStartup.cs
并使用 Cookie 标头的标头传播效果很好。它还避免了有关正确处理您的处理程序和客户端的所有问题。请注意,如果请求 cookie 的传播不是您需要的(抱歉,操作),您可以在配置客户端工厂时设置自己的 cookie。
IServiceCollection
services.AddHttpClient("MyNamedClient").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
options.Headers.Add("Cookie");
});
IApplicationBuilder
builder.UseHeaderPropagation();
IHttpClientFactory
你的控制器或中间件。using var client = clientFactory.CreateClient("MyNamedClient");