有时我想用 HTTPClient 从我的 ASP.NET 网站调用内部资源(ASP.NET Webforms 和 MVC 一起运行)。
第一个障碍是表单身份验证 cookie,我想我已经解决了,但第二个问题是当我调用 MVC 控制器时,System.Web.HttpContext.Current.Session.SessionID 与我发起调用时不同。SessionID 被用作缓存项目的键,因此这些项目在控制器中返回 null。
所以我的问题归结为这一点,我是否正确实现了 cookie 交换,如果 httpClient 有一个会话,它可以从它的主机继承会话吗?
try
{
// Boostrap the properties tab by preloading data
Uri baseAddress = new Uri(Request.Url.GetLeftPart(UriPartial.Authority));
CookieContainer cookieContainer = new CookieContainer();
string resource = string.Format("/Contact/PropertyBootstrapper/{0}", Request.Params["ContactGuid"]);
HttpCookie appCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
using (HttpClientHandler handler = new HttpClientHandler { CookieContainer = cookieContainer })
using (HttpClient client = new HttpClient(handler) { BaseAddress = baseAddress })
{
Debug.Assert(appCookie != null, "appCookie != null");
cookieContainer.Add(baseAddress, new Cookie(appCookie.Name,appCookie.Value));
HttpResponseMessage response = client.GetAsync(resource).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync();
}
}
}
catch (Exception exception)
{
System.Diagnostics.Trace.WriteLine(exception);
}