在一个wpf应用程序中,我必须调用一个外部休息服务,该服务返回一个带有会话ID的cookie。在所有后续调用中,我必须在cookie中发送会话ID,否则它不会返回任何数据。
那么如何在课后的wpf代码中检索cookie?
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
var domain = EndPoint;
HttpResponseMessage response2 = client.PostAsync(domain, new StringContent(parameters)).Result;
Uri uri = new Uri(domain);
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
var cookieWithId = responseCookies.Single(o => o.Name == "JESSSIONID");
其中EndPoint有http://mydomain.com:38080/workshop/且参数有rest / login?username = usr&amp; password = pwd
答案 0 :(得分:1)
以下是有关如何从响应中读取Cookie的示例。
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
var domain = "http://yourServiceURL.com";
HttpResponseMessage response = client.GetAsync(domain).Result;
Uri uri = new Uri(domain);
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
var cookieWithId = responseCookies.Single(o => o.Name == "SessionId");