我在WinForms应用程序中使用HttpClient
时遇到了一种奇怪的行为(尝试连接到Azure网站托管的Web API)。
简单来说:
http://xxx.azurewebsites.net/api/entity
),然后返回客户端并尝试连接,它可以正常工作。只有在我首先尝试通过浏览器进行连接后,才会导致连接变为authorized
?
编辑:
这是我的代码:
public static User GetUser()
{
HttpClient client = StaticFunctions.GetHttpClient();
string parameters = "username=username&password=password"
HttpResponseMessage response = client.GetAsync("api/user?" + parameters).Result;
if (response.IsSuccessStatusCode)
{
var user = response.Content.ReadAsAsync<User>().Result;
return user;
}
else
{
return null;
}
}
public static HttpClient GetHttpClient()
{
NetworkCredential credentials = null;
if (GlobalVariables.CurrentUser != null)
{
credentials = new NetworkCredential(GlobalVariables.CurrentUser.UserName, GlobalVariables.CurrentUser.Password);
}
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = false;
handler.Credentials = credentials;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(PublicClasses.GlobalVariables.BaseUriString);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}