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