在响应的Headers中获取
string[] Cookie = (string[])response.Headers.GetValues(“Set-Cookie”);
CookieValue = Cookie[0].Split(‘;’)[0];
文章参考
https://blog.csdn.net/qq_39569480/article/details/122559682
https://blog.csdn.net/qq_39569480/article/details/112608041
https://blog.csdn.net/qq_39569480/article/details/108996039
using(HttpClient client = new HttpClient()) 非注入方式
{
string responseBody = string.Empty;
client.DefaultRequestHeaders.Add("Method", "Post");
var content = new StringContent(parameter, Encoding.UTF8, ContentType);
if (!string.IsNullOrEmpty(AuthType))
{
switch (AuthType)
{
//Bearer认证 如果接口未加密省略此行
case "Bearer": client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); break;
case "Cookie": client.DefaultRequestHeaders.Add("Cookie", token); break;
}
//var authorizationBased64 = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{userName}:{password}"));//basic认证方式 用户名:密码 然后base64加密
//client.DefaultRequestHeaders.Add("Authorization", authorizationBased64);
}
HttpResponseMessage response = await client.PostAsync(Url, content);
//response.EnsureSuccessStatusCode();
if (response.StatusCode == HttpStatusCode.OK)
{
responseBody = response.Content.ReadAsStringAsync().Result;
dynamic res = JsonConvert.DeserializeObject<dynamic>(responseBody);
string CookieValue = "";
if (AuthType == "Cookie"&& Url.EndsWith("login")) {
string[] Cookie = (string[])response.Headers.GetValues("Set-Cookie");
CookieValue = Cookie[0].Split(';')[0];
}
return new { ok = true, isTryException = false, cookie = CookieValue, data = res };
}
else
{
responseBody = response.Content.ReadAsStringAsync().Result;
return new { ok = false, isTryException = false, cookie = "", data = responseBody };
}
}