我正在尝试使用Web api HttpClient向需要登录的终结点发布帖子,该终结点需要以标识帐户的HTTP cookie的形式登录(这只是#ifdef发行版本中未包含的内容)。
HttpClient
#ifdef
如何向其中添加Cookie HttpRequestMessage?
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(); }