C# HttpリクエストサーバーレスポンスのCookieを取得する

1. C# サーバーが Cookie を保存するために応答します

        public IActionResult Test2()
        {
            Response.Cookies.Append("user","张三丰");
            Response.Cookies.Append("pwd", "123");
            return Content("输出cookie成功:张三丰");
        }

 

2. C# は HTTP リクエストを送信し、応答 Cookie を取得します

使用: CookieContainer

string url = "http://localhost:5082/cookie/test2";
var cookies = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookies };
HttpClient client = new HttpClient(handler);

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("name", "abc");
FormUrlEncodedContent content = new FormUrlEncodedContent(dic);
content.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");
HttpResponseMessage resp = client.PostAsync(url, content).Result;
//获取相应获取cookie
string cookie = cookies.GetCookieHeader(new Uri(url));
Console.WriteLine(cookie);//输出:user=%E5%BC%A0%E4%B8%89%E4%B8%B0; pwd=123
Console.WriteLine(resp.Content.ReadAsStringAsync().Result);

 印刷結果:

 

もっと:

C# は cookie を使用して http リクエストを送信します_C# は Cookie を使用してリクエストを送信します

C# Post はフォームデータ型データを送信します - .Net Core

照合順序を使用した _C# Regex を使用した C# 正規表現

おすすめ

転載: blog.csdn.net/u011127019/article/details/131154190