ITypedHttpClientFactory<TClient> 接口

定义

组件的工厂抽象,它可使用自定义配置为给定逻辑名称创建类型化客户端实例。

generic <typename TClient>
public interface class ITypedHttpClientFactory
public interface ITypedHttpClientFactory<TClient>
type ITypedHttpClientFactory<'Client> = interface
Public Interface ITypedHttpClientFactory(Of TClient)

类型参数

TClient

要创建的类型化客户端的类型。

示例

此示例显示了用于定义类型化客户端类的基本模式。

class ExampleClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger _logger;

    // typed clients can use constructor injection to access additional services
    public ExampleClient(HttpClient httpClient, ILogger<ExampleClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    // typed clients can expose the HttpClient for application code to call directly
    public HttpClient HttpClient => _httpClient;

    // typed clients can also define methods that abstract usage of the HttpClient
    public async Task SendHelloRequest()
    {
        var response = await _httpClient.GetAsync("/helloworld");
        response.EnsureSuccessStatusCode();
    }
}

此示例演示如何从 ASP.NET Core中间件使用类型化客户端。

// in Startup.cs
public void Configure(IApplicationBuilder app, ExampleClient exampleClient)
{
    app.Run(async (context) =>
    {
        var response = await _exampleClient.GetAsync("/helloworld");
        await context.Response.WriteAsync("Remote server said: ");
        await response.Content.CopyToAsync(context.Response.Body);
    });
}

此示例演示如何从 ASP.NET Core MVC 控制器使用类型化客户端。

// in Controllers/HomeController.cs
public class HomeController : ControllerBase(IApplicationBuilder app, ExampleClient exampleClient)
{
    private readonly ExampleClient _exampleClient;

    public HomeController(ExampleClient exampleClient)
    {
        _exampleClient = exampleClient;
    }

    public async Task<IActionResult> Index()
    {
        var response = await _exampleClient.GetAsync("/helloworld");
        var text = await response.Content.ReadAsStringAsync();
        return Content("Remote server said: " + text, "text/plain");
    };
}

注解

ITypedHttpClientFactory<TClient>是支持 AddHttpClient<TClient>(IServiceCollection, String)AddTypedClient<TClient>(IHttpClientBuilder) 功能的基础结构。 此类型很少应该直接在应用程序代码中使用,而是使用 GetService(Type) 来检索类型化客户端。

可以通过调用 AddHttpClient(IServiceCollection)在 中IServiceCollection注册默认值ITypedHttpClientFactory<TClient>。 默认值 ITypedHttpClientFactory<TClient> 将在服务集合中注册为单一实例开放泛型服务。

默认 ITypedHttpClientFactory<TClient> 使用类型激活来创建类型化客户端实例。 类型化客户端类型不是直接从 中检索的 IServiceProvider。 有关详细信息,请参阅CreateInstance(IServiceProvider, Type, Object[])

方法

CreateClient(HttpClient)

对于关联的 HttpClient,创建类型化客户端。

适用于