向 IHttpFactory 构建的客户端添加摘要身份验证

问题描述 投票:0回答:1

我正在构建一个 API,它公开一个 POST 端点,该端点接受请求中包含映射到 uri 的键的环境详细信息。然后这个API根据传递的请求数据,将POST请求发送到其他API。

到目前为止,客户端的基本 uri 是静态的,现在 uri 是动态的,并且是从传入请求传递的。

通过构造函数注入时,HttpClient 会构建在 Service 类中。

如何在已由构造函数构建的客户端上添加 CredentialsCache,并控制从启动到按需请求的逻辑?

当前使用扩展方法在 Startup 上注册

public static IServiceCollection AddUnderTest(this IServiceCollection services, ClientA settings)
    {
        var client = services
            .AddHttpClient(
            nameof(ClientA),
            c => { c.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); });

        client.ConfigurePrimaryHttpMessageHandler(
            handler => new HttpClientHandler
            {
                Credentials = new CredentialCache { {
                    new Uri(""),
                    "Digest",
                    new NetworkCredential(settings.Username, settings.Password) } }
            });
        return services;
    }

服务舱

public class MyService
{

    public MyService(IHttpClientFactory htpClientFactory)
    {
        var myClient = htpClientFactory.CreateClient("ClientA");
        //add digest auth and credentials here, and not on startup
    }
}

如何在启动时添加与扩展方法中相同的配置?

c# .net-core credentials digest httpclientfactory
1个回答
0
投票

根据 CarnaViire 的回复here,似乎如果我们想使用 IHttpClientFactory 动态设置凭证摘要身份验证,我们必须为每个调用手动设置请求标头。这是设置摘要身份验证标头的示例

https://callumhoughton18.github.io/Personal-Site/blog/digest-auth-in-dotnet/

© www.soinside.com 2019 - 2024. All rights reserved.