gpt4 book ai didi

C# Refit 客户端不发送授权 header

转载 作者:行者123 更新时间:2023-12-05 05:42:00 34 4
gpt4 key购买 nike

我正在使用 C# Refit客户端让我的服务通过 http 相互通信。

我正在尝试通过 Authorization header 发送 Bearer token ,但根据错误消息,它没有在请求中设置 AZ header (见底部)。我已经尝试通过提供所有 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.ApiExceptionRequestMessage.Headers 不包含 Authorization header 。

下面是我如何注册 retrofit 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 header :

Error

我做错了什么?如何让它发送 AZ header ?

最佳答案

第一次尝试:

services.AddRefitClient<T>(new RefitSettings { AuthorizationHeaderValueGetter = () => Task.FromResult("TestToken") }).ConfigureHttpClient(ConfigureHttpClient);

第二次尝试:

services.AddRefitClient<T>().ConfigureHttpClient(ConfigureHttpClient).AddHttpMessageHandler<AuthorizationMessageHandler>();

哪里:

  public class AuthorizationMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancelToken)
{
HttpRequestHeaders headers = request.Headers;

AuthenticationHeaderValue authHeader = headers.Authorization;

if (authHeader != null)
headers.Authorization = new AuthenticationHeaderValue(authHeader.Scheme, "TestToken");

return await base.SendAsync(request, cancelToken);
}
}

关于C# Refit 客户端不发送授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72172657/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com