I have an app that uses ASP.NET Core MVC as the client and ASP.NET Core WEB API on the back-end. I use a helper method to help me send all the requests to the API and get the response. I am unable to figure out how to handle 403 responses from the API at one place(using something like middleware or filter).
I don't want to do an error code check in every action of a controller. I want to know if we can intercept the response between lines 1 and 2 in the code below.
var response = httpClient.SendRequest(request);
if(response.StatusCode == StatusCodes.Status403Forbidden) {
// redirect to some page.
}
I have tried to add a middleware(like shown below) to do the same and included at the beginning of the startup.cs class but the response in the context is always 500 and not the correct error code(403 in this case).
public async Task Invoke(HttpContext context)
{
if (context.Response.StatusCode == StatusCodes.Status403Forbidden)
{
context.Response.Redirect("Page to redirect");
}
await _next.Invoke(context);
}
Whenever there is an error code(Ex: 403 forbidden) sent from the API, I would like to redirect the users to a specific page from a single place and don't want to check for the status code in every action.