Hus*_*man 15 c# middleware asp.net-core-mvc asp.net-core asp.net-core-webapi
我正在使用ASP.NET Core Web API,我有多个独立的web api项目.在执行任何控制器的操作之前,我必须检查登录用户是否已经模仿其他用户(我可以从中获取DB)并且可以将模拟用户传递Id给actions.
由于这是一段可以重复使用的代码,我想我可以使用中间件:
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)
更好的解决方案是使用范围服务.看看这个: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)
| 归档时间: |
|
| 查看次数: |
5872 次 |
| 最近记录: |