简体   繁体   English

使用工厂方法创建类型化的HTTP客户端ASP.NET Core 2.1

[英]Using factory method to create typed HTTP client, ASP.NET Core 2.1

I'm following guides/docs on registering HTTP client within my application. 我正在遵循有关在我的应用程序中注册HTTP客户端的指南/文档。 There are couple of services I need to call so I decided to go with "Typed clients". 我需要打电话给几个服务,所以我决定使用“类型客户”。

In order to call another service I need to use OAuth - since this is service-to-service call, when I obtain access token, I cache it + I have setup periodical refresh of token. 为了调用另一个服务,我需要使用OAuth-因为这是服务到服务的调用,所以当我获取访问令牌时,我会对其进行缓存+我已经设置了令牌的定期刷新。 This means there's another component IAccessTokenCache which gives me access token for service. 这意味着还有另一个组件IAccessTokenCache ,它为我提供了服务的访问令牌。

Thing I'm struggling to figure out is how to register and configure my typed HTTP client providing it also dependency on IAccessTokenCache . 我正在努力弄清的是如何注册和配置键入的HTTP客户端, IAccessTokenCache它也依赖于IAccessTokenCache

I'm using ASP.NET Core 2.1 (crucial detail, read on). 我正在使用ASP.NET Core 2.1(重要细节,请继续阅读)。

HTTP client wrapper looks like this (from: HttpClientFactory in ASP.NET Core 2.1 (Part 2) ): HTTP客户端包装看起来像这样(来自: ASP.NET Core 2.1(第2部分)中的HttpClientFactory ):

public class ServiceFooClient
{
    public ServiceFooClient(HttpClient client)
    {
        Client = client;
    }

    public HttpClient Client { get; }
}

And this is how I register and configure client: 这就是我注册和配置客户端的方式:

services
    .AddHttpClient<ServiceFooClient>(
        c =>
        {
            c.BaseAddress = new Uri("https://www.foo.svc");

            // TODO: grab particular access token from cache
            c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "...");
        })
    .AddHttpMessageHandler<ResponseMonitorHandler>()
    .ConfigureHttpMessageHandlerBuilder(
        b =>
        {
            var handler =
                b.AdditionalHandlers.OfType<ResponseMonitorHandler>().FirstOrDefault();

            if (handler != null)
            {
                handler.ServiceName = "Foo Service";
            }
        });

... I'm already configuring HTTP client and even adding my custom HTTP handler. ...我已经在配置HTTP客户端,甚至添加了自定义HTTP处理程序。 You can see exact point where I want to access IAccessTokenCache , but I can't. 您可以看到要访问IAccessTokenCache确切点,但是我不能。

Possible solutions I can think of: 我能想到的可能解决方案:

Configure underlying HttpClient in ServiceFooClient wrapper, like: ServiceFooClient包装器中配置基础HttpClient ,例如:

// ctor
public ServiceFooClient(HttpClient httpClient, IAccessTokenCache tokenCache)
{
    Client = httpClient;
    Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenCache.GetToken("Foo"));
}

This could work nicely, except I don't configuration decoupling - suddenly dedicated HTTP client has part of configuration in Startup (base URI, additional HTTP handler) and another part in wrapping class (setting authorization header). 这可以很好地工作,除非我不进行配置解耦-突然,专用的HTTP客户端在Startup中配置了一部分(基本URI,其他HTTP处理程序),在包装类中又配置了一部分(设置授权标头)。

Not using AddHttpClient extension method (and others) 不使用AddHttpClient扩展方法(及其他)

I don't really need to call HttpClientFactoryServiceCollectionExtensions.AddHttpClient<T>(...) - I could do all that stuff myself. 我真的不需要调用HttpClientFactoryServiceCollectionExtensions.AddHttpClient<T>(...) -我可以自己做所有这些事情。 But as lazy developer... I don't even want to finish this sentence. 但是作为懒惰的开发人员……我什至不想结束这句话。 There's quite a lot of registering inside, so this is just big no no for me. 内部有很多注册,所以对我来说这是很大的不。

Upgrade to ASP.NET Core 2.2 升级到ASP.NET Core 2.2

Related to previous point - in 2.1, there's no overload of AddHttpClient (2.2: AddHttpClient<TClient>(this IServiceCollection services, Action<IServiceProvider, HttpClient> configureClient) ) which would accept callback with service provider. 与上一点有关-在2.1中,不会接受将接受服务提供者回调的AddHttpClient (2.2: AddHttpClient<TClient>(this IServiceCollection services, Action<IServiceProvider, HttpClient> configureClient) )的重载。 Upgrading to 2.2 would be probably the best solution, yet I will have to be pretty sure that nothing else gets broken (and I already know that there is/was BC break with getting/setting request tracing ID on HTTP context). 升级到2.2可能是最好的解决方案,但是我必须确保没有其他问题(并且我已经知道BC中断了/在HTTP上下文中获取/设置请求跟踪ID)。 This could be potentially risky, so I'm trying first to solve my issue in scope of 2.1. 这可能有潜在的风险,所以我首先尝试解决2.1范围内的问题。

Compare branch of 2.1 with 2.2: HttpClientFactoryServiceCollectionExtensions 将2.1的分支与2.2进行比较: HttpClientFactoryServiceCollectionExtensions

Custom HTTP handler setting request headers 自定义HTTP处理程序设置请求标头

Same way as I now register ResponseMonitorHandler , I could register HTTP handler which has access to IAccessTokenCache and sets request authorization header. 与现在注册ResponseMonitorHandler方式相同,我可以注册可访问IAccessTokenCache并设置请求授权标头的HTTP处理程序。

But again, as in first case, this decouples configuration of HTTP client. 但是同样,与第一种情况一样,这会取消HTTP客户端的配置。 Also if I had several different access tokens, I would either need to implement several HTTP handlers or do some logic deciding what token from cache to use based on request properties. 同样,如果我有几个不同的访问令牌,我要么需要实现几个HTTP处理程序,要么做一些逻辑,根据请求属性来决定要使用缓存中的哪个令牌。

Finally, question : is there any other way I didn't consider? 最后,问题 :还有其他我没有考虑的方法吗? Is there easy solution of this in ASP.NET 2.1? 在ASP.NET 2.1中是否有简单的解决方案? (... apart of just copy-pasting method from 2.2 of course) (...当然只是2.2版中的复制粘贴方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core 2.1:将客户端证书添加到已注册的类型化 HTTP 客户端 - ASP.NET Core 2.1: Add client certificate to registered typed HTTP clients HTTP 客户端补丁方法与 Asp.net 核心 2.1,错误请求 - HTTP Client Patch method with Asp.net core 2.1, bad request 如何在ASP.NET Core 2.1应用程序中注册类型化HttpClient - How to register a Typed HttpClient in a ASP.NET Core 2.1 application 如何在ASP.NET Core中将HTTP响应干净地传播到类型化HTTP客户端的使用者 - How to propagate HTTP responses cleanly to consumers of a typed HTTP client in ASP.NET Core 在 asp.net core 中创建范围工厂 - Create scope factory in asp.net core HTTP Get方法的SSL握手异常-ASP.NET Core 2.1 - SSL Handshake exception for HTTP Get method - ASP.NET core 2.1 使用ASP.NET Core 2.1和UWP应用程序作为客户端的SignalR Webhost返回&#39;405 Method not allowed&#39; - SignalR Webhost with ASP.NET Core 2.1 and UWP app as Client returns ' 405 Method not allowed' 如何在ASP.NET Core 2.1中获取客户端IP地址 - How to get Client IP address in ASP.NET Core 2.1 ASP.NET Core 2.1 在 App Engine 中没有 HTTP/HTTPS 重定向 - ASP.NET Core 2.1 no HTTP/HTTPS redirection in App Engine 使用 ASP.NET 核心 DI 容器注册“类型化”gRPC 客户端 - Registering a “typed” gRPC client with the ASP.NET Core DI container
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM