HttpClient可以共享HttpContext.Current.Session.SessionID作为其主机吗?

时间:2013-07-23 21:57:28

标签: asp.net asp.net-mvc-3

有些时候,我希望使用HTTPClient从我的ASP.NET网站内部调用内部资源(ASP.NET Webforms和MVC一起运行)。

第一个障碍是表单auth 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);
}

1 个答案:

答案 0 :(得分:2)

您只需对会话cookie执行相同操作 - 从上下文复制到客户端。会话cookie带有CookieID。