我正在使用 ASP.NET Core Web API
,其中我有多个独立的 Web API 项目。在执行 Controller 的任何操作之前,我必须检查登录用户是否已经在模拟其他用户(我可以从 DB
获得)并且可以传递模拟用户 Id
到 actions
。
由于这是一段可以重用的代码,我想我可以使用一个中间件:
- 我可以从请求 header 获取初始用户登录信息
- 获取模拟的用户 ID(如果有)
- 将该 ID 注入(inject)请求管道中,使其可供被调用的 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);
}
}
我找到了这个 Question ,但这并没有解决我正在寻找的问题。
如何传递参数并使其在请求管道中可用?在 header 中传递它是否可以,或者有更优雅的方法来做到这一点?
最佳答案
您可以使用 HttpContext.Items 在管道内传递任意值:
context.Items["some"] = "value";
关于c# - ASP.NET Core 中间件向 Controller 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788152/