我已经通过使用博客中的方法解决了这个问题:http: //soabubblog.wordpress.com/2013/07/10/web-api-httpclient-authentication/
以下帮助方法用于登录服务。
static class AuthenticationService
{
public static HttpClient CreateAuthenticatedSession(out HttpStatusCode statusCode)
{
var Client = new HttpClient
{
BaseAddress = new Uri(@" http://localhost:52310/ ")
};
var Result = Client.PostAsync("/Account/WebLogOn/",
new FormUrlEncodedContent(
new Dictionary<string, string>
{
{"UserName", "test"},
{"Password", "1234"}
}
)
).Result;
//Result.EnsureSuccessStatusCode();
statusCode = Result.StatusCode;
return Client;
}
}
以下客户端代码是发送请求并获取结果。
void GetProductList()
{
HttpStatusCode statusCode;
var httpClientSession
= Helpers.AuthenticationService.CreateAuthenticatedSession(out statusCode);
if (statusCode == HttpStatusCode.OK)
{
httpClientSession.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = httpClientSession.GetAsync("/api/product").Result;
// Result.EnsureSuccessStatusCode();
if (result.StatusCode == HttpStatusCode.OK)
{
string responseText = result.Content.ReadAsStringAsync().Result;
}
else
{
string errorText = string.Format("[{0}] - Cannot get the product list.", result.StatusCode);
}
}
else
{
string errorText1 = "Authentication Failed";
}
}