1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it helped me to set OData error body for 403 error code produced by Authorization filter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.