Hi @Salvatore Sanollo,
For how to custom middleware you could check this official document.
For your current scenario by using HttpClient, a better way is to custom DelegatingHandler
public class RedirectUnAuthorizedHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
public RedirectUnAuthorizedHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
_httpContextAccessor.HttpContext.Response.Redirect("/Account/Login");
}
return response;
}
}
Be sure register the services in the Startup.cs or Program.cs (beyond .NET 6).
builder.Services.AddHttpClient("MyApi")
.AddHttpMessageHandler<RedirectUnAuthorizedHandler>();
builder.Services.AddSingleton<RedirectUnAuthorizedHandler>();
builder.Services.AddHttpContextAccessor();
//.....
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Call the api:
public class HomeController : Controller
{
public HomeController(IHttpClientFactory factory)
{
_client = factory.CreateClient("MyApi");
}
private readonly HttpClient _client;
public async Task<IActionResult> Index()
{
var res = await _client.GetAsync("https://localhost:xxxx/Your_Api_URL");
return View();
}
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,
Rena