Priyanka
Priyanka

Reputation: 136

Intercept API Response(Error code: 403) using a ASP.NET Core Middleware

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.

Upvotes: 1

Views: 1930

Answers (1)

XavierAM
XavierAM

Reputation: 1775

You can use the UseStatusCodePagesWithReExecute provided middleware.

You can register it with like that (depending on the action you actually want to perform) :

 app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");

The interpolated variable {0} contains the status code, and it can be passed to the controller called during reexecution, in this case the HomeController, Method Error.

Hope this helps.

Upvotes: 1

Related Questions