C# 使用HttpClient与WebClient C调用web API时出现的问题#
我试图通过使用C# 使用HttpClient与WebClient C调用web API时出现的问题#,c#,asp.net-web-api,C#,Asp.net Web Api,我试图通过使用HttpClient进行web API调用,但得到未授权错误。我在头中传递密钥,但它仍然给我这个错误。我可以在小提琴手轨迹中看到我的钥匙 如果我使用WebClient,那么我会得到一个成功的响应请求在两种方法中都是相同的 使用HttpClient: #region HttpClient using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost");
HttpClient
进行web API调用,但得到未授权
错误。我在头中传递密钥,但它仍然给我这个错误。我可以在小提琴手轨迹中看到我的钥匙
如果我使用WebClient
,那么我会得到一个成功的响应<代码>请求
在两种方法中都是相同的
使用HttpClient:
#region HttpClient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apiKey", "MyKey");
var content = JsonConvert.SerializeObject(request);
var response = await client.PostAsJsonAsync("https://MyUrl", content);
if (response.IsSuccessStatusCode)
{
deliveryManagerQuoteResponse = await response.Content.ReadAsAsync<DeliveryManagerQuoteResponse>();
}
else
{
var reasonPhrase = response.ReasonPhrase;
if (reasonPhrase.ToUpper() == "NOT AUTHORIZED")
{
throw new KeyNotFoundException("Not authorized");
}
}
}
#endregion
#region WebClient
// Create string to hold JSON response
string jsonResponse = string.Empty;
using (var client = new WebClient())
{
try
{
client.UseDefaultCredentials = true;
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
client.Headers.Add("apiKey", "MyKey");
var uri = new Uri("https://MyUrl");
var content = JsonConvert.SerializeObject(request);
var response = client.UploadString(uri, "POST", content);
jsonResponse = response;
}
catch (WebException ex)
{
// Http Error
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var webResponse = (HttpWebResponse)ex.Response;
var statusCode = (int)webResponse.StatusCode;
var msg = webResponse.StatusDescription;
throw new HttpException(statusCode, msg);
}
else
{
throw new HttpException(500, ex.Message);
}
}
}
#endregion
第一件事第一
其次,您是否使用fiddler查看这两个请求的外观?您应该能够看到标题看起来会有所不同。现在,您正在使用授权头,它实际上将执行与您所希望的不同的操作。您只需添加一个常规的“ol头”:
client.DefaultRequestHeaders.Add("apiKey", "MyKey");
第一件事第一。其次,您是否使用fiddler查看这两个请求的外观?您应该能够看到标题看起来会有所不同。尝试添加:
client.DefaultRequestHeaders.Add(“apiKey”、“MyKey”)代码>成功了。谢谢。很高兴听到它起作用了@maccettura,添加答案,这样他就可以将其标记为已接受。感谢@maccettura链接/引用“您使用的HttpClient是错误的…”宝贵信息,不应丢失/忽略!希望大家花点时间阅读链接“您使用的HttpClient错误…”。有价值的信息不是直观的,也不能直接解决用户询问的问题。