C# HttpClientでCookieを設定する

先週に引き続いて、HttpClientネタです。

WebサイトにHttpClientを使ってフォーム認証を行い、Cookieをリクエストに詰めて取り回す必要がありましたので、備忘録としておきます。

  1. フォームでユーザ名・パスワードの情報を詰めたリクエストをPOSTして、レスポンスヘッダのSet-Cookieの値を取得する
  2. 認証Cookieを使って更にPOSTリクエストする
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

// 1. Cookieの取得
var client = new HttpClient();
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
    { "username", "ohke" },
    { "password", "ohkepassword" }
});
var loginResponse = await httpClient.PostAsync("https://hogehoge.xxx.com/login");
// HeadersプロパティからSet-Cookieの値を取得する
var cookie = loginResponse.Headers.GetValues("Set-Cookie").First();

// 2. Cookieの設定
content = new FormUrlEncodedContent(new Dictionary<string, string>
{
    { "key", "value" }
});
// リクエストのCookieヘッダに1.で取得した値を設定する
content.Headers.Add("Cookie", cookie);
var response = await httpClient.PostAsync("https://hogehoge.xxx.com/other", content);