【发布时间】:2017-08-04 21:59:43
【问题描述】:
我正在使用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);
}
}
我找到了这个Question,但这并没有解决我要找的问题。
如何传递参数并使其在请求管道中可用?可以在标题中传递它还是有更优雅的方法来做到这一点?
【问题讨论】:
-
您应该更改请求上下文,而不是管道本身。
-
@LexLi,您能否举例说明一下,您的意思是向请求本身添加一些信息并从控制器获取信息?如果那是你的意思,我在想那个,但又在哪里,查询,身体,这不会影响被调用的动作吗?
标签: c# asp.net-core asp.net-core-mvc middleware asp.net-core-webapi