【发布时间】:2023-04-01 07:00:01
【问题描述】:
我有一个使用 HttpClient 调用 ASP.NET Core WebApi 的 ASP.NET Core MVC 应用程序,但我必须发送授权标头,问题是我的 HttpClient 不会发送授权标头。
我有一个用于调用具有以下构造函数的 webapi 的服务:
public ApiService(HttpClient httpClient, IHttpContextAccessor accessor)
{
string token = accessor.HttpContext.User.FindFirstValue("JWToken"); // gets user token
httpClient.BaseAddress = new Uri(AppSettings.BaseUrlApi); //sets the base URL of the webapi
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.Timeout = TimeSpan.FromMinutes(1);
httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", token);
_httpClient = httpClient; // assigns to a private property "private readonly HttpClient _httpClient;"
}
然后,当我将数据发布到 webapi 时,我使用以下方法:
public async Task<User> PostAsync(string url, User user)
{
StringContent jsonContent = new StringContent(
JsonConvert.SerializeObject(user, Formatting.Indented, _jsonSettings), // _jsonSettings is a JsonSerializerSettings object
Encoding.UTF8,
"application/json");
using HttpResponseMessage httpResponse =
await _httpClient.PostAsync(url, jsonContent);
httpResponse.EnsureSuccessStatusCode();
string responseString = await httpResponse.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<User>(responseString, _jsonSettings);
}
对于不需要 Authorization 标头的请求,它工作得很好,但它不发送 Authorization 标头,我尝试使用 HttpRequestMessage 然后 SendAsync 实例化一个新的 HttClient,但它从来没有工作,我也尝试过使用httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); 但它不起作用,也使用TryAddWithoutValidation,但不起作用。
最糟糕的是,当我检查我的 httpClient 对象时,授权令牌就在那里:
然后我从我的 webapi 收到一条 401 消息,当我检查在 webapi 中收到的请求时,授权标头为空,并且我的 webapi 在收到来自 ajax 调用或诸如 insomnia 和 postman 之类的应用程序的请求时工作正常.
我无法弄清楚我错过了什么。
编辑:
我的授权标头是 {}
现在,例如,当我收到来自 insomnia 的请求时,我有以下标头:
【问题讨论】:
-
尝试添加一个日志处理程序,如本例所示:docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/…,以便您可以观察原始请求属性
标签: c# asp.net asp.net-web-api