How do I set a cookie on HttpClient's HttpRequestMessage

后端 未结 5 1203
眼角桃花
眼角桃花 2020-11-22 09:57

I am trying to use the web api\'s HttpClient to do a post to an endpoint that requires login in the form of an HTTP cookie that identifies an account (this is o

5条回答
  •  暖寄归人
    2020-11-22 10:09

    The accepted answer is the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandler defaults to using its CookieContainer property for cookies. If you disable that then by setting UseCookies to false you can set cookie headers manually and they will appear in the request, e.g.

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

提交回复
热议问题