我正在尝试使用Web api的HttpClient在需要登录的终结点计算机上发布终结点,该终结点必须以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();
}

关于c# - 如何在HttpClient的HttpRequestMessage上设置Cookie,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12373738/

10-11 05:17
查看更多