ITypedHttpClientFactory<TClient> 介面

定義

元件的 Factory 抽象概念,可以使用指定邏輯名稱的自訂組態來建立具類型用戶端執行個體。

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,建立具類型用戶端。

適用於