简体   繁体   English

使用ASP.NET核心中间件拦截API响应(错误代码:403)

[英]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. 我有一个应用程序,它使用ASP.NET Core MVC作为客户端和后端的ASP.NET Core WEB API。 I use a helper method to help me send all the requests to the API and get the response. 我使用帮助器方法来帮助我将所有请求发送到API并获得响应。 I am unable to figure out how to handle 403 responses from the API at one place(using something like middleware or filter). 我无法弄清楚如何在一个地方处理来自API的403响应(使用类似中间件或过滤器的东西)。

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. 我想知道我们是否可以在下面的代码中拦截第1行和第2行之间的响应。

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). 我试图添加一个中间件(如下所示)来做同样的事情,并包含在startup.cs类的开头,但上下文中的响应总是500而不是正确的错误代码(在这种情况下为403)。

  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. 每当从API发送错误代码(Ex:403 forbidden)时,我想将用户从一个地方重定向到特定页面,并且不希望在每个操作中检查状态代码。

You can use the UseStatusCodePagesWithReExecute provided middleware. 您可以使用UseStatusCodePagesWithReExecute提供的中间件。

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. 插值变量{0}包含状态代码,它可以传递给在重新执行期间调用的控制器,在本例中为HomeController,Method Error。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM