首页 > 解决方案 > 如何在 ASP NET Core 3.1 中任何控制器的每个方法中检查/重定向?

问题描述

我正在寻找一种在每个控制器的每个方法中执行此操作的方法,即使对于那些不返回 IActionResult 的方法(我将继续讨论):

  1. 获取 User.Claim 以获取登录到站点的用户信息。
  2. 检查用户是否在数据库中被阻止(我自己的存储库已经在工作)
  3. 将用户重定向到显示“您被阻止”的页面,就像 Exceptions 的工作流程一样。

我已经做出的考虑和尝试:

现在我正在尝试做一个中间件,但我是 NET Core 中的新手,所以我也无法编译。也在尝试从 ViewStart 调用我的 userRepository

标签: c#asp.netasp.net-coreasp.net-core-middleware

解决方案


最好的方法是使用中间件。这里有一个例子:

internal class UserMiddleware
{
    private readonly RequestDelegate next;
    private readonly IUserRepository userRepository;

    public UserMiddleware(RequestDelegate next, IUserRepository userRepository)
    {
        this.next = next ?? throw new ArgumentNullException(nameof(next));
        this.userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
    }

    public async Task Invoke(HttpContext httpContext)
    {
        Claim clientId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier);
        bool isBlocked = await this.userRepository.CheckUser(clientId);

        if (isBlocked)
        {
            await httpContext.Response.WriteAsync("You are blocked.");
            return;
        }

        await this.next(httpContext);
    }
}

然后在您的启动方法中,您应该在映射控制器之前调用它:

public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Other stuff...

    app.UseMiddleware<UserMiddleware>();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

推荐阅读