Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Note
This isn't the latest version of this article. For the current release, see the .NET 11 version of this article.
By Kirk Larkin, Steve Gordon, Glenn Condron, and Ryan Nowak.
You can register the IHttpClientFactory and use it to configure and create HttpClient instances in an app. The IHttpClientFactory interface offers the following benefits:
Provides a central location for naming and configuring logical
HttpClientinstances. For example, a client named github can be registered and configured to access GitHub. A default client can be registered for general access.Codifies the concept of outgoing middleware via delegating handlers in the
HttpClientinstance. Provides extensions for Polly-based middleware to take advantage of delegating handlers inHttpClient.Manages the pooling and lifetime of underlying
HttpClientMessageHandlerinstances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managingHttpClientlifetimes.Adds a configurable logging experience (via the
ILogger) for all requests sent through clients created by the factory.
This article describes how to make HTTP requests by using IHttpClientFactory in ASP.NET Core applications. The sample code version uses System.Text.Json to deserialize JSON content returned in HTTP responses. For samples that use Json.NET and ReadAsAsync<T>, use the browser Version selector to select a 2.x version of this article.
Review consumption patterns
There are several ways IHttpClientFactory can be used in an app:
The best approach depends upon the app's requirements.
Basic usage
Register IHttpClientFactory by calling the AddHttpClient method in the Program.cs file:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddHttpClient();
An IHttpClientFactory can be requested by using dependency injection (DI). The following code uses IHttpClientFactory to create an HttpClient instance:
public class BasicModel : PageModel
{
private readonly IHttpClientFactory _httpClientFactory;
public BasicModel(IHttpClientFactory httpClientFactory) =>
_httpClientFactory = httpClientFactory;
public IEnumerable<GitHubBranch>? GitHubBranches { get; set; }
public async Task OnGet()
{
var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get,
"https://api.github.com/repos/dotnet/AspNetCore.Docs/branches")
{
Headers =
{
{ HeaderNames.Accept, "application/vnd.github.v3+json" },
{ HeaderNames.UserAgent, "HttpRequestsSample" }
}
};
var httpClient = _httpClientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
GitHubBranches = await JsonSerializer.DeserializeAsync
<IEnumerable<GitHubBranch>>(contentStream);
}
}
}
In the example, the call to IHttpClientFactory is a good way to refactor an existing app. This approach has no effect on how HttpClient is used.
In scenarios where HttpClient instances are created in an existing app, replace the occurrences with calls to the CreateClient.
Named clients
Named clients are suitable for the following scenarios:
- The app requires many distinct uses of
HttpClient. - There are many
HttpClientinstances with different configurations.
Specify the configuration for a named HttpClient instance during its registration in the Program.cs file:
builder.Services.AddHttpClient("GitHub", httpClient =>
{
httpClient.BaseAddress = new Uri("https://api.github.com/");
// using Microsoft.Net.Http.Headers;
// The GitHub API requires two headers.
httpClient.DefaultRequestHeaders.Add(
HeaderNames.Accept, "application/vnd.github.v3+json");
httpClient.DefaultRequestHeaders.Add(
HeaderNames.UserAgent, "HttpRequestsSample");
});
In the code snippet, the client is configured with:
- The base address
https://api.github.com/. - Two headers required to work with the GitHub API.
CreateClient method
For each call to the CreateClient:
- A new instance of
HttpClientis created. - The configuration action is called.
To create a named client, pass the client name into the CreateClient method:
public class NamedClientModel : PageModel
{
private readonly IHttpClientFactory _httpClientFactory;
public NamedClientModel(IHttpClientFactory httpClientFactory) =>
_httpClientFactory = httpClientFactory;
public IEnumerable<GitHubBranch>? GitHubBranches { get; set; }
public async Task OnGet()
{
var httpClient = _httpClientFactory.CreateClient("GitHub");
var httpResponseMessage = await httpClient.GetAsync(
"repos/dotnet/AspNetCore.Docs/branches");
if (httpResponseMessage.IsSuccessStatusCode)
{
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
GitHubBranches = await JsonSerializer.DeserializeAsync
<IEnumerable<GitHubBranch>>(contentStream);
}
}
}
In the code snippet, the request doesn't need to specify a hostname. The code can pass the path only because the base address configured for the client is used.
Typed clients
Typed clients provide several benefits:
- Access to the same capabilities as named clients without the need to use strings as keys.
- IntelliSense and compiler help when consuming clients.
- The ability to define a single location to configure and interact with a particular
HttpClientinstance. For example, a single typed client might be used for a single backend endpoint, or to encapsulate all logic dealing with the endpoint. - Support for DI and injection where the app requires the functionality.
A typed client accepts an HttpClient parameter in its constructor:
public class GitHubService
{
private readonly HttpClient _httpClient;
public GitHubService(HttpClient httpClient)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri("https://api.github.com/");
// using Microsoft.Net.Http.Headers;
// The GitHub API requires two headers.
_httpClient.DefaultRequestHeaders.Add(
HeaderNames.Accept, "application/vnd.github.v3+json");
_httpClient.DefaultRequestHeaders.Add(
HeaderNames.UserAgent, "HttpRequestsSample");
}
public async Task<IEnumerable<GitHubBranch>?> GetAspNetCoreDocsBranchesAsync() =>
await _httpClient.GetFromJsonAsync<IEnumerable<GitHubBranch>>(
"repos/dotnet/AspNetCore.Docs/branches");
}
In the code snippet:
- The configuration is moved into the typed client.
- The provided
HttpClientinstance is stored as a private field.
API-specific methods can be created that expose HttpClient functionality. For example, the GetAspNetCoreDocsBranches method encapsulates code to retrieve docs GitHub branches.
The following code calls AddHttpClient in the Program.cs file to register the GitHubService typed client class:
builder.Services.AddHttpClient<GitHubService>();
The typed client is registered as transient with DI. In the snippet, the AddHttpClient method registers GitHubService as a transient service. This registration uses a factory method to:
- Create an instance of
HttpClient. - Create an instance of
GitHubServiceand passing in the instance ofHttpClientto its constructor.
The typed client can be injected and consumed directly:
public class TypedClientModel : PageModel
{
private readonly GitHubService _gitHubService;
public TypedClientModel(GitHubService gitHubService) =>
_gitHubService = gitHubService;
public IEnumerable<GitHubBranch>? GitHubBranches { get; set; }
public async Task OnGet()
{
try
{
GitHubBranches = await _gitHubService.GetAspNetCoreDocsBranchesAsync();
}
catch (HttpRequestException)
{
// ...
}
}
}
The configuration for a typed client can also be specified during its registration in the Program.cs file, rather than in the typed client's constructor:
builder.Services.AddHttpClient<GitHubService>(httpClient =>
{
httpClient.BaseAddress = new Uri("https://api.github.com/");
// ...
});
Generated clients
The IHttpClientFactory interface can be used in combination with third-party libraries such as Refit. Refit is a REST library for .NET that converts C# interfaces into HTTP clients using source generation at compile time. Call the AddRefitClient method to register the interface as a typed HttpClient for making external HTTP calls.
A custom interface represents the external API:
public interface IGitHubClient
{
[Get("/repos/dotnet/AspNetCore.Docs/branches")]
Task<IEnumerable<GitHubBranch>> GetAspNetCoreDocsBranchesAsync();
}
Call AddRefitClient to generate the dynamic implementation, and then call the ConfigureHttpClient method to configure the underlying HttpClient instance:
builder.Services.AddRefitClient<IGitHubClient>()
.ConfigureHttpClient(httpClient =>
{
httpClient.BaseAddress = new Uri("https://api.github.com/");
// using Microsoft.Net.Http.Headers;
// The GitHub API requires two headers.
httpClient.DefaultRequestHeaders.Add(
HeaderNames.Accept, "application/vnd.github.v3+json");
httpClient.DefaultRequestHeaders.Add(
HeaderNames.UserAgent, "HttpRequestsSample");
});
Use DI to access the dynamic implementation of IGitHubClient:
public class RefitModel : PageModel
{
private readonly IGitHubClient _gitHubClient;
public RefitModel(IGitHubClient gitHubClient) =>
_gitHubClient = gitHubClient;
public IEnumerable<GitHubBranch>? GitHubBranches { get; set; }
public async Task OnGet()
{
try
{
GitHubBranches = await _gitHubClient.GetAspNetCoreDocsBranchesAsync();
}
catch (ApiException)
{
// ...
}
}
}
Make POST, PUT, and DELETE requests
In the preceding examples, all HTTP requests use the GET HTTP verb. HttpClient also supports other HTTP verbs, including:
- POST
- PUT
- DELETE
- PATCH
For a complete list of supported HTTP verbs, see the HttpMethod.
The following example shows how to make an HTTP POST request:
public async Task CreateItemAsync(TodoItem todoItem)
{
var todoItemJson = new StringContent(
JsonSerializer.Serialize(todoItem),
Encoding.UTF8,
Application.Json); // using static System.Net.Mime.MediaTypeNames;
using var httpResponseMessage =
await _httpClient.PostAsync("/api/TodoItems", todoItemJson);
httpResponseMessage.EnsureSuccessStatusCode();
}
In the preceding code, the CreateItemAsync method:
- Serializes the
TodoItemparameter to JSON by usingSystem.Text.Json. - Creates an instance of StringContent to package the serialized JSON for sending in the HTTP request body.
- Calls the PostAsync to send the JSON content to the specified URL. The value is a relative URL that is added to the HttpClient.BaseAddress.
- Calls the EnsureSuccessStatusCode to throw an exception if the response status code doesn't indicate success.
HttpClient also supports other types of content. For example, MultipartContent and StreamContent. For a complete list of supported content, see HttpContent.
The following example shows an HTTP PUT request:
public async Task SaveItemAsync(TodoItem todoItem)
{
var todoItemJson = new StringContent(
JsonSerializer.Serialize(todoItem),
Encoding.UTF8,
Application.Json);
using var httpResponseMessage =
await _httpClient.PutAsync($"/api/TodoItems/{todoItem.Id}", todoItemJson);
httpResponseMessage.EnsureSuccessStatusCode();
}
The code snippet is similar to the POST example. The SaveItemAsync method calls the PutAsync instead of PostAsync.
The following example shows an HTTP DELETE request:
public async Task DeleteItemAsync(long itemId)
{
using var httpResponseMessage =
await _httpClient.DeleteAsync($"/api/TodoItems/{itemId}");
httpResponseMessage.EnsureSuccessStatusCode();
}
In the code snippet, the DeleteItemAsync method calls DeleteAsync. Because HTTP DELETE requests typically contain no body, the DeleteAsync method doesn't provide an overload that accepts an instance of HttpContent.
To learn more about using different HTTP verbs with HttpClient, see HttpClient.
Use outgoing request middleware
HttpClient has the concept of delegating handlers that can be linked together for outgoing HTTP requests. The IHttpClientFactory interface provides the following benefits:
- Define the handlers to apply for each named client by using a simplified process.
- Register and chain multiple handlers to build an outgoing request middleware pipeline. Each handler can perform work before and after the outgoing request. This pattern is similar to the inbound middleware pipeline in ASP.NET Core.
- Manage cross-cutting concerns around HTTP requests, such as caching, error handling, serialization, and logging.
To create a delegating handler:
- Derive from the DelegatingHandler.
- Override the SendAsync. Execute code before passing the request to the next handler in the pipeline:
public class ValidateHeaderHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.Headers.Contains("X-API-KEY"))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(
"The API key header X-API-KEY is required.")
};
}
return await base.SendAsync(request, cancellationToken);
}
}
The code snippet checks if the X-API-KEY header is in the request. If X-API-KEY is missing, the code returns the BadRequest status code.
More than one handler can be added to the configuration for an HttpClient instance by using the AddHttpMessageHandler:
builder.Services.AddTransient<ValidateHeaderHandler>();
builder.Services.AddHttpClient("HttpMessageHandler")
.AddHttpMessageHandler<ValidateHeaderHandler>();
In the code snippet, ValidateHeaderHandler is registered with DI as a transient service. A delegating handler must be registered in DI as a transient service, rather than singleton or scoped. Delegating handlers can't be reused across multiple HTTP client pipelines, and registering a handler as a singleton results in an InvalidOperationException when the handler is reused. After registration, AddHttpMessageHandler can be called, passing in the type for the handler.
Multiple handlers can be registered in the order they should execute. Each handler wraps the next handler until the final HttpClientHandler executes the request:
builder.Services.AddTransient<SampleHandler1>();
builder.Services.AddTransient<SampleHandler2>();
builder.Services.AddHttpClient("MultipleHttpMessageHandlers")
.AddHttpMessageHandler<SampleHandler1>()
.AddHttpMessageHandler<SampleHandler2>();
In the code snippet, SampleHandler1 runs first, before SampleHandler2.
Use DI in outgoing request middleware
When IHttpClientFactory creates a new delegating handler, it uses DI to fulfill the handler's constructor parameters. IHttpClientFactory creates a separate DI scope for each handler, which can lead to surprising behavior when a handler consumes a scoped service.
Consider the following interface and its implementation, which represents a task as an operation with an identifier, OperationId:
public interface IOperationScoped
{
string OperationId { get; }
}
public class OperationScoped : IOperationScoped
{
public string OperationId { get; } = Guid.NewGuid().ToString()[^4..];
}
As the name suggests, IOperationScoped is registered with DI by using a scoped lifetime:
builder.Services.AddScoped<IOperationScoped, OperationScoped>();
The following delegating handler consumes and uses IOperationScoped to set the X-OPERATION-ID header for the outgoing request:
public class OperationHandler : DelegatingHandler
{
private readonly IOperationScoped _operationScoped;
public OperationHandler(IOperationScoped operationScoped) =>
_operationScoped = operationScoped;
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Add("X-OPERATION-ID", _operationScoped.OperationId);
return await base.SendAsync(request, cancellationToken);
}
}
In the HttpRequestsSample download, run the app and browse to the /Operation page, then refresh. The request scope value changes for each request, but the handler scope value only changes every 5 seconds.
Handlers can depend upon services of any scope. Services that handlers depend upon are disposed when the handler is disposed.
Use one of the following approaches to share per-request state with message handlers:
- Pass data into the handler by using the Options.
- Use the IHttpContextAccessor to access the current request.
- Create a custom AsyncLocal<T> storage object for passing the data.
Use Polly-based handlers
The IHttpClientFactory interface integrates with the third-party library Polly. Polly is a comprehensive resilience and transient fault-handling library for .NET. It allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.
Extension methods are provided to enable the use of Polly policies with configured HttpClient instances. The Polly extensions support adding Polly-based handlers to clients. Polly requires the Microsoft.Extensions.Http.Polly NuGet package.
Handle transient faults
Faults typically occur when external HTTP calls are transient. AddTransientHttpErrorPolicy allows a policy to be defined to handle transient errors. Policies configured with the AddTransientHttpErrorPolicy method handle the following responses:
- HttpRequestException
- HTTP 5xx
- HTTP 408
AddTransientHttpErrorPolicy provides access to a PolicyBuilder object configured to handle errors representing a possible transient fault:
builder.Services.AddHttpClient("PollyWaitAndRetry")
.AddTransientHttpErrorPolicy(policyBuilder =>
policyBuilder.WaitAndRetryAsync(
3, retryNumber => TimeSpan.FromMilliseconds(600)));
In the code snippet, a WaitAndRetryAsync policy is defined. Failed requests are retried up to three times with a delay of 600 ms between attempts.
Dynamically select policies
Extension methods are provided to add Polly-based handlers, for example, the AddPolicyHandler. The following AddPolicyHandler overload inspects the request to decide which policy to apply:
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(10));
var longTimeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(30));
builder.Services.AddHttpClient("PollyDynamic")
.AddPolicyHandler(httpRequestMessage =>
httpRequestMessage.Method == HttpMethod.Get ? timeoutPolicy : longTimeoutPolicy);
In the code snippet, if the outgoing request is an HTTP GET, a 10-second timeout is applied. For any other HTTP method, a 30-second timeout is used.
Add multiple Polly handlers
It's common practice to nest Polly policies:
builder.Services.AddHttpClient("PollyMultiple")
.AddTransientHttpErrorPolicy(policyBuilder =>
policyBuilder.RetryAsync(3))
.AddTransientHttpErrorPolicy(policyBuilder =>
policyBuilder.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
This example adds two handlers:
The first handler uses the AddTransientHttpErrorPolicy to add a retry policy. Failed requests are retried up to three times.
The second
AddTransientHttpErrorPolicycall adds a circuit breaker policy. Further external requests are blocked for 30 seconds if five failed attempts occur sequentially. Circuit breaker policies are stateful. All calls through this client share the same circuit state.
Add policies from the Polly registry
An approach to managing regularly used policies is to define them once and register them with a PolicyRegistry. For example:
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(10));
var longTimeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(30));
var policyRegistry = builder.Services.AddPolicyRegistry();
policyRegistry.Add("Regular", timeoutPolicy);
policyRegistry.Add("Long", longTimeoutPolicy);
builder.Services.AddHttpClient("PollyRegistryRegular")
.AddPolicyHandlerFromRegistry("Regular");
builder.Services.AddHttpClient("PollyRegistryLong")
.AddPolicyHandlerFromRegistry("Long");
The code snippet adds two policies to the Polly registry, Regular and Long. The code calls the AddPolicyHandlerFromRegistry to configure individual named clients to use these policies from the Polly registry.
For more information on IHttpClientFactory and Polly integrations, see the Polly wiki.
HttpClient and lifetime management
A new HttpClient instance is returned each time CreateClient is called on the IHttpClientFactory. An HttpMessageHandler is created for each named client. The factory manages the lifetimes of the HttpMessageHandler instances.
IHttpClientFactory pools the HttpMessageHandler instances created by the factory to reduce resource consumption. An HttpMessageHandler instance might be reused from the pool when creating a new HttpClient instance, if its lifetime isn't expired.
Pooling of handlers is desirable as each handler typically manages its own underlying HTTP connections. Creating more handlers than necessary can result in connection delays. Some handlers also keep connections open indefinitely, which can prevent the handler from reacting to DNS changes.
The default handler lifetime is 2 minutes. The default value can be overridden on a per-named client basis:
builder.Services.AddHttpClient("HandlerLifetime")
.SetHandlerLifetime(TimeSpan.FromMinutes(5));
HttpClient instances can generally be treated as .NET objects that don't require disposal. Disposal cancels outgoing requests and guarantees the given HttpClient instance can't be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances.
Keeping a single HttpClient instance alive for a long duration is a common pattern used before the inception of IHttpClientFactory. This pattern becomes unnecessary after migrating to IHttpClientFactory.
Explore alternatives to IHttpClientFactory
Using IHttpClientFactory in a DI-enabled app avoids:
- Resource exhaustion problems by pooling
HttpMessageHandlerinstances. - Stale DNS problems by cycling
HttpMessageHandlerinstances at regular intervals.
There are alternative ways to solve the preceding problems by using a long-lived SocketsHttpHandler instance.
- Create an instance of
SocketsHttpHandlerwhen the app starts and use it for the life of the app. - Configure PooledConnectionLifetime to an appropriate value based on DNS refresh times.
- Create
HttpClientinstances by usingnew HttpClient(handler, disposeHandler: false)as needed.
The alternate approaches solve the resource management problems that IHttpClientFactory solves in a similar way.
- The
SocketsHttpHandlershares connections acrossHttpClientinstances. This sharing prevents socket exhaustion. - The
SocketsHttpHandlercycles connections according toPooledConnectionLifetimeto avoid stale DNS problems.
Log messages and response status
Clients created via IHttpClientFactory record log messages for all requests. Enable the appropriate information level in the logging configuration so you can see the default log messages. Other logging, such as the logging of request headers, is only included at trace level.
The log category used for each client includes the name of the client. A client named MyNamedClient, for example, logs messages with a category of "System.Net.Http.HttpClient.MyNamedClient.LogicalHandler." Messages that have the LogicalHandler suffix occur outside the request handler pipeline. On the request, messages are logged before any other handlers in the pipeline process them. On the response, messages are logged after any other pipeline handlers receive the response.
Logging also occurs inside the request handler pipeline. In the MyNamedClient example, those messages are logged with the log category "System.Net.Http.HttpClient.MyNamedClient.ClientHandler." For the request, the logging occurs after all other handlers run and immediately before the request is sent. On the response, the logging includes the state of the response before it passes back through the handler pipeline.
Enabling logging outside and inside the pipeline enables inspection of the changes made by the other pipeline handlers. The logging might include changes to request headers or to the response status code.
Including the name of the client in the log category enables log filtering for specific named clients.
Configure the HttpMessageHandler
It might be necessary to control the configuration of the inner HttpMessageHandler used by a client.
An IHttpClientBuilder is returned when adding named or typed clients. The ConfigurePrimaryHttpMessageHandler extension method can be used to define a delegate. The delegate is used to create and configure the primary HttpMessageHandler used by that client:
builder.Services.AddHttpClient("ConfiguredHttpMessageHandler")
.ConfigurePrimaryHttpMessageHandler(() =>
new HttpClientHandler
{
AllowAutoRedirect = true,
UseDefaultCredentials = true
});
Work with cookies
The pooled HttpMessageHandler instances results in CookieContainer objects being shared. Unanticipated CookieContainer object sharing often results in incorrect code.
For apps that require cookies, consider:
- Disabling automatic cookie handling
- Avoiding
IHttpClientFactory
Call ConfigurePrimaryHttpMessageHandler to disable automatic cookie handling:
builder.Services.AddHttpClient("NoAutomaticCookies")
.ConfigurePrimaryHttpMessageHandler(() =>
new HttpClientHandler
{
UseCookies = false
});
Use IHttpClientFactory in a console app
In a console app, add the following package references to the project:
In the following example:
- IHttpClientFactory and
GitHubServiceare registered in the Generic Host's service container. GitHubServiceis requested from DI, which in-turn requests an instance ofIHttpClientFactory.GitHubServiceusesIHttpClientFactoryto create an instance ofHttpClient, which it uses to retrieve docs GitHub branches.
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddHttpClient();
services.AddTransient<GitHubService>();
})
.Build();
try
{
var gitHubService = host.Services.GetRequiredService<GitHubService>();
var gitHubBranches = await gitHubService.GetAspNetCoreDocsBranchesAsync();
Console.WriteLine($"{gitHubBranches?.Count() ?? 0} GitHub Branches");
if (gitHubBranches is not null)
{
foreach (var gitHubBranch in gitHubBranches)
{
Console.WriteLine($"- {gitHubBranch.Name}");
}
}
}
catch (Exception ex)
{
host.Services.GetRequiredService<ILogger<Program>>()
.LogError(ex, "Unable to load branches from GitHub.");
}
public class GitHubService
{
private readonly IHttpClientFactory _httpClientFactory;
public GitHubService(IHttpClientFactory httpClientFactory) =>
_httpClientFactory = httpClientFactory;
public async Task<IEnumerable<GitHubBranch>?> GetAspNetCoreDocsBranchesAsync()
{
var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get,
"https://api.github.com/repos/dotnet/AspNetCore.Docs/branches")
{
Headers =
{
{ "Accept", "application/vnd.github.v3+json" },
{ "User-Agent", "HttpRequestsConsoleSample" }
}
};
var httpClient = _httpClientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
httpResponseMessage.EnsureSuccessStatusCode();
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync
<IEnumerable<GitHubBranch>>(contentStream);
}
}
public record GitHubBranch(
[property: JsonPropertyName("name")] string Name);
Use header propagation middleware
Header propagation is an ASP.NET Core middleware to propagate HTTP headers from the incoming request to the outgoing HttpClient requests. To use header propagation:
Install the Microsoft.AspNetCore.HeaderPropagation package.
Configure the
HttpClientinstance and middleware pipeline in the Program.cs file:// Add services to the container. builder.Services.AddControllers(); builder.Services.AddHttpClient("PropagateHeaders") .AddHeaderPropagation(); builder.Services.AddHeaderPropagation(options => { options.Headers.Add("X-TraceId"); }); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseHttpsRedirection(); app.UseHeaderPropagation(); app.MapControllers();Make outbound requests by using the configured
HttpClientinstance, which includes the added headers.
Related content
ASP.NET Core