Hi @Nayan Choudhary
From your description, it seems that you want to add the HttpMessageHandler to the specify controller. In this scenario, you can refer to the following code:
In the Program.cs file:
builder.Services.AddControllersWithViews();
// Register the delegatehandler
builder.Services.AddTransient<MyDelegateHandler>();
// Add HttpClient and configure a specific HttpMessageHandler for a controller
builder.Services.AddHttpClient<HomeController>("YourHttpClientName", client =>
{
// Configure your HttpClient settings here, if needed
client.BaseAddress=new Uri("https://localhost:7079/");
})
.AddHttpMessageHandler<MyDelegateHandler>(); // Add your custom HttpMessageHandler
In the HomeController: Use the HttpClientFactory to create httpclient.
public class HomeController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public HomeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<IActionResult> Index()
{
var _client = _httpClientFactory.CreateClient("YourHttpClientName");
using (HttpResponseMessage response = await _client.GetAsync("/api/Values"))
{
try
{
var result = await response.Content.ReadAsStringAsync();
return Ok(result);
}
catch (Exception e)
{
Console.WriteLine("Failed to read content");
return Ok("Failed");
}
}
}
In the DelegatingHandler:
public sealed class MyDelegateHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// THIS IS WHAT I EXPECT TO BE EXECUTED!!!!
Console.WriteLine("Hello from MyDelegateHandler!");
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
After that, the result as below:
Reference: Make HTTP requests using IHttpClientFactory in ASP.NET Core
Update:
Besides, you can also refer to the following sample code to use a typed HttpClient.
MyRepositoryClient.cs file:
public interface IMyRepositoryClient
{
Task<string> GetAsync();
}
public class MyRepositoryClient : IMyRepositoryClient
{
private readonly HttpClient _client;
private readonly ILogger<MyRepositoryClient> _logger;
public MyRepositoryClient(HttpClient client, ILogger<MyRepositoryClient> logger)
{
_client = client;
_logger = logger;
}
public async Task<string> GetAsync()
{
using (HttpResponseMessage response = await _client.GetAsync("/api/Values"))
{
try
{
return await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Failed to read content");
return null;
}
}
}
}
MyDelegateHandler.cs
public sealed class MyDelegateHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//
Console.WriteLine("Hello from MyDelegateHandler!");
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
Program.cs file:
// Register the delegatehandler
builder.Services.AddTransient<MyDelegateHandler>();
builder.Services.AddTransient<IMyRepositoryClient, MyRepositoryClient>();
builder.Services.AddHttpClient<IMyRepositoryClient, MyRepositoryClient>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://localhost:7079/"))
.AddHttpMessageHandler<MyDelegateHandler>();
HomeController:
public class HomeController : Controller
{
private readonly IMyRepositoryClient _myclient;
public HomeController(IMyRepositoryClient httpClientFactory)
{
_myclient = httpClientFactory;
}
public async Task<IActionResult> Index()
{
var result = await _myclient.GetAsync();
return Ok(result);
}
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion