我正在使用ASP.NET Core Web API,我有多个独立的web api项目。在执行任何控制器的操作之前,我必须检查登录用户是否已经模仿其他用户(我可以从DB获取)并且可以将模拟的用户ID传递给操作。
由于这是一段可以重复使用的代码,我想我可以使用中间件:
- 我可以从请求标头获取初始用户登录
- 获取被授权的用户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);
}
}
我找到了这个 题,但这没有解决我正在寻找的问题。
如何传递参数并使其在请求管道中可用?是否可以将其传递到标题中或者有更优雅的方式来执行此操作?