Reputation: 6363
There are times when I want to make calls with the HTTPClient from within my ASP.NET Web Site to internal resources ( ASP.NET Webforms and MVC running together).
The first hurdle was the forms auth cookie, which I think I solved, the second problem though is that when I call my MVC controller, the System.Web.HttpContext.Current.Session.SessionID is different than when I initiated the call. The SessionID is being used as a key to cache items, thus the items come back null in the controller.
So my question boils down to this, did I implement the cookie swapping correctly and can the httpClient inherit the session from it's host if it has one?
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);
}
Upvotes: 1
Views: 3277
Reputation: 48230
You just do the same with the session cookie - copy from the context to the client. The session cookie carries the CookieID.
Upvotes: 2