我正在使用 C# Refit 客户端使我的服务通过 http 通信。
我尝试通过设置 Authorization 头来发送 Bearer token,但根据错误信息,请求中没有设置 AZ header(参见底部)。我已尝试通过提供所有头信息和使用
这是我的 Refit 客户端 API 调用定义:
然而,我收到了401错误,并且查看抛出的
我尝试通过设置 Authorization 头来发送 Bearer token,但根据错误信息,请求中没有设置 AZ header(参见底部)。我已尝试通过提供所有头信息和使用
[Authorize]
属性以及他们在自述文件中描述的所有其他方法来设置它。这是我的 Refit 客户端 API 调用定义:
[Post(PresentationsBasePath + "/{presentationId}/cart")]
Task AddItemToCartAsync(long presentationId, ShoppingCartItemView item, [HeaderCollection] IDictionary<string, string> headers);
//calling it here:
await _api.AddItemToCartAsync(presentationId, item, GetTokenHeader(presentationId, token));
private Dictionary<string, string> GetTokenHeader(long presentationId, string token) => new()
{
["pres_id"] = presentationId.ToString(),
[HeaderNames.Authorization] = $"Bearer {token}",
};
然而,我收到了401错误,并且查看抛出的
Refit.ApiException
,发现RequestMessage.Headers
中没有包含授权头信息。
以下是我注册refit api IPresentationsApi
的方式。我在DI配置中未进行任何与认证相关的操作。
var refitSettings = GetRefitSettings();
void Configure<T>() where T : class => services
.AddRefitClient<T>()
.ConfigureHttpClient(ConfigureHttpClient);
Configure<IMarsPresentationApi>();
//other apis configured below
private static void ConfigureHttpClient(IServiceProvider sp, HttpClient client)
{
var config = sp.GetRequiredService<IMarsConfiguration>();
if (config.BaseUrl == null)
throw new InvalidOperationException("Mars:BaseUrl must be configured");
client.BaseAddress = new Uri(config.BaseUrl);
}
这里显示了错误-您可以看到我收到了401错误,并且请求中未设置AZ头:
我做错了什么?如何使其发送AZ头?
[HeaderNames.Authorization] = $"Bearer {token}",
- DLeh[POST]
请求。 - DLeh