ASP.NET核心中间件将参数传递给控制器

Hus*_*man 15 c# middleware asp.net-core-mvc asp.net-core asp.net-core-webapi

我正在使用ASP.NET Core Web API,我有多个独立的web api项目.在执行任何控制器的操作之前,我必须检查登录用户是否已经模仿其他用户(我可以从中获取DB)并且可以将模拟用户传递Idactions.

由于这是一段可以重复使用的代码,我想我可以使用中间件:

  • 我可以从请求标头获取初始用户登录
  • 获取被授权的用户ID(如果有)
  • 在请求管道中注入该ID,使其可用于被调用的api
public class GetImpersonatorMiddleware
{
    private readonly RequestDelegate _next;
    private IImpersonatorRepo _repo { get; set; }

    public GetImpersonatorMiddleware(RequestDelegate next, IImpersonatorRepo imperRepo)
    {
        _next = next;
        _repo = imperRepo;
    }
    public async Task Invoke(HttpContext context)
    {
        //get user id from identity Token
        var userId = 1;

        int impersonatedUserID = _repo.GetImpesonator(userId);

        //how to pass the impersonatedUserID so it can be picked up from controllers
        if (impersonatedUserID > 0 )
            context.Request.Headers.Add("impers_id", impersonatedUserID.ToString());

        await _next.Invoke(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

我找到了这个问题,但这没有解决我正在寻找的问题.

如何传递参数并使其在请求管道中可用?将它传递到标题中是否可以,或者有更优雅的方法来执行此操作?

Ric*_*res 11

您可以使用HttpContext.Items在管道内传递任意值:

context.Items["some"] = "value";
Run Code Online (Sandbox Code Playgroud)

  • 另请参阅:[使用HttpContext.Items](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state#working-with-httpcontextitems) (3认同)

Mot*_*mbo 7

更好的解决方案是使用范围服务.看看这个:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x#per-request-dependencies

您的代码应如下所示:

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext, IImpersonatorRepo imperRepo)
    {
        imperRepo.MyProperty = 1000;
        await _next(httpContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将您的ImpersonatorRepo注册为:

services.AddScoped<IImpersonatorRepo, ImpersonatorRepo>()
Run Code Online (Sandbox Code Playgroud)

  • 当您尝试在中间件之外使用每个请求的服务时,这不起作用。请参阅 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-3.1#per-request-middleware-dependencies (3认同)