有時候我想用HTTPClient從ASP.NET網站內部資源(ASP.NET Webforms和MVC一起運行)進行調用。HttpClient可以共享HttpContext.Current.Session.SessionID作爲它的主機嗎?
第一個障礙是表單身份驗證cookie,我認爲我解決了,但第二個問題是,當我打電話給我的MVC控制器時,System.Web.HttpContext.Current.Session.SessionID與我啓動時不同電話。 SessionID被用作緩存項目的鍵,因此項目在控制器中返回爲空。
所以我的問題歸結爲這一點,我是否正確實施了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);
}
您只需執行會話cookie即可 - 從上下文複製到客戶端。 –
@WiktorZychla你能寫一個答案,我會接受它。謝謝 –