ASP.NET Web API pass in forms authentication to HttpClient

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi,
I have two projects:
First project: Forms-authenticated ASP.NET Web API secured using forms <br/>
authentication with its controllers annotated with <br/>
System.Web.Http.AuthorizeAttribute . The database it connects to <br/>
has a valid user and data.
Second project: Forms-authenticated ASP.NET MVC project also secured using <br/>
forms authentication with its controllers annotated with <br/>
System.Web.Mvc.AuthorizeAttribute . The database it connects to <br/>
is exactly the same database as the one the first project connects to.
I am already able to access the api if I authenticate myself in the MVC <br/>
project by logging in and then browsing to the url of the web <br/>
api ; no problem because the data returns.
Now comes the tricky part: I want to use HttpClient to retrieve the <br/>
data instead of browsing to it from the URL.
In my ASP.NET MVC controller, I want to use HttpClient to access the Web API <br/>
controller. Among other things, I tried this:
<pre class="prettyprint WebRequestHandler handler = new WebRequestHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
var results = client.GetAsync(string.Format("{0}{1}",
ConfigurationManager.AppSettings["WebApiBaseUri"].ToString(),
"Employees")).Result;
results.EnsureSuccessStatusCode();
IEnumerable<EmployeeModel> returnModel = results.Content.ReadAsAsync<IEnumerable<EmployeeModel>>().Result;<br/>[/code]
but I keep on getting "401: Unauthorized" back.
Heres the question: how are you supposed to pass in the forms-authenticated <br/>
credentials to HttpClient so I can retrieve the data back from the Web API?
Thanks a lot in advance

View the full article
 
Back
Top