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.
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:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
and also this attribute on my service class:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
and tried to pass all the cookies from HttpContext to HttpClient instance using WebRequestHandler() handler:
var handler = new WebRequestHandler();
CookieContainer cc = new CookieContainer();
for (int i = 0; i < 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)){}
web.config:
<authentication mode="Forms">
<forms defaultUrl="~/" loginUrl="~/Account/Login"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
<location path="Service/TestService.svc">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
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.
-Thanks