【问题标题】:ASP.NET Core Middleware Passing Parameters to ControllersASP.NET Core 中间件向控制器传递参数
【发布时间】: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


【解决方案1】:

您可以使用 HttpContext.Items 在管道内传递任意值:

context.Items["some"] = "value";

【讨论】:

  • 我正在使用会话。 context.Session.SetInt32("user-id", 12345); 哪种方法最好,为什么?
  • 会话可能启用也可能不启用,它们需要 cookie。
  • 这似乎仍然是在中间件管道之外存储值的唯一有效解决方案。
【解决方案2】:

更好的解决方案是使用范围服务。看看这个:Per-request middleware 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);
    }
}

然后将您的 ImpersonatorRepo 注册为:

services.AddScoped<IImpersonatorRepo, ImpersonatorRepo>()

【讨论】:

猜你喜欢
  • 2018-12-15
  • 2021-02-09
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 2015-01-10
  • 2010-09-14
  • 2021-08-19
  • 1970-01-01
相关资源
最近更新 更多