ITypedHttpClientFactory<TClient> Interfaz

Definición

Una abstracción de fábrica para un componente que puede crear instancias de cliente con tipo mediante una configuración personalizada para un nombre lógico determinado.

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

Parámetros de tipo

TClient

Tipo de cliente con tipo que se va a crear.

Ejemplos

En este ejemplo se muestra el patrón básico para definir una clase de cliente con tipo.

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();
    }
}

En este ejemplo se muestra cómo consumir un cliente con tipo desde un middleware de 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);
    });
}

En este ejemplo se muestra cómo consumir un cliente con tipo desde un controlador MVC de ASP.NET Core.

// 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");
    };
}

Comentarios

es la ITypedHttpClientFactory<TClient> infraestructura que admite la AddHttpClient<TClient>(IServiceCollection, String) funcionalidad y AddTypedClient<TClient>(IHttpClientBuilder) . Este tipo rara vez se debe usar directamente en el código de la aplicación, use GetService(Type) en su lugar para recuperar clientes con tipo.

Un valor predeterminado ITypedHttpClientFactory<TClient> se puede registrar en un IServiceCollection mediante una llamada a AddHttpClient(IServiceCollection). El valor predeterminado ITypedHttpClientFactory<TClient> se registrará en la colección de servicios como un servicio genérico de apertura singleton.

El valor predeterminado ITypedHttpClientFactory<TClient> usa la activación de tipos para crear instancias de cliente con tipo. Los tipos de cliente con tipo no se recuperan directamente de .IServiceProvider Para obtener información detallada, vea CreateInstance(IServiceProvider, Type, Object[]).

Métodos

CreateClient(HttpClient)

Crea un cliente con tipo dado un objeto HttpClient asociado.

Se aplica a