title: WCF with Forms Authentication
body: <p>I've a asp.net 4.5 webforms project with WCF REST services. The aspx pages call these services from code behind using HttpClient. All the get and post services work fine.</p>
  
  <p>We recently added Forms Authentication to the whole solution and it redirects to the login page when I try to access any page or WCF service (ex: localhost/Service/Test.svc). When I login and try to hit the service from aspx page's code behind using HttpClient, it doesn't pick up my HttpContext on WCF and instead returns me the html of the login page. I've the following added to the WCF settings in web.config:</p>
  
  <pre><code>&lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" /&gt;
  </code></pre>
  
  <p>and also this attribute on my service class:</p>
  
  <pre><code>[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
  </code></pre>
  
  <p>and tried to pass all the cookies from HttpContext to HttpClient instance using WebRequestHandler() handler:</p>
  
  <pre><code>var handler = new WebRequestHandler();
                  CookieContainer cc = new CookieContainer();
                  for (int i = 0; i &lt; Request.Cookies.Count; i++)
                  {
                      Cookie oC = new Cookie();
                   // Convert between the System.Net.Cookie to a System.Web.HttpCookie...
                      oC.Domain   = "ss";
                      oC.Expires  = Request.Cookies[i].Expires;
                      oC.Name     = Request.Cookies[i].Name;
                      oC.Path     = Request.Cookies[i].Path;
                      oC.Secure   = Request.Cookies[i].Secure;
                      oC.Value    = Request.Cookies[i].Value;
                      cc.Add(oC);
                  }
                  handler.CookieContainer = cc;
                  handler.UseDefaultCredentials = true;
                  handler.AllowPipelining = true;
                  handler.UseCookies = true;                
                  using (var client = new HttpClient(handler)){}
  </code></pre>
  
  <p>web.config: </p>
  
  <pre><code>&lt;authentication mode="Forms"&gt; 
    &lt;forms defaultUrl="~/" loginUrl="~/Account/Login"&gt;&lt;/forms&gt; 
  &lt;/authentication&gt; 
  &lt;authorization&gt; 
    &lt;deny users="?"/&gt; 
  &lt;/authorization&gt; 
  &lt;/system.web&gt; 
  &lt;location path="Service/TestService.svc"&gt; 
   &lt;system.web&gt; 
    &lt;authorization&gt; 
     &lt;allow users="*"/&gt; 
    &lt;/authorization&gt; 
   &lt;/system.web&gt; 
  &lt;/location&gt;
  </code></pre>
  
  <p>Am I doing something wrong in the code or is it not possible for the WCF service to be on same project as the client and use the HttpContext? Please let me know if more code is required. I'm not sure what should I provide as not much of it is that complicated.</p>
  
  <p>-Thanks</p>