c# - ASP.NET Core 中间件向 Controller 传递参数

标签 c# asp.net-core asp.net-core-mvc middleware asp.net-core-webapi

我正在使用 ASP.NET Core Web API,其中我有多个独立的 Web API 项目。在执行 Controller 的任何操作之前,我必须检查登录用户是否已经在模拟其他用户(我可以从 DB 获得)并且可以传递模拟用户 Idactions

由于这是一段可以重用的代码,我想我可以使用一个中间件:

  • 我可以从请求 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/

相关文章:

c# - 在 Entity Framework 中删除之前更新

configuration - ASP.NET Core 向 DI 注入(inject)服务公开配置

c# - MVC6,如果用户从 View 中提交空的十进制/整数值,服务器端模型验证将显示错误消息

c# - 为什么 LinkedListNode Next 属性是只读的?

时间:2019-03-17 标签:c#regeximgsrc

c# - 访问 startup.cs 中的 appsetting.json 值

javascript - MVC - 我的表单没有传递我的选择下拉列表的选定选项

c# - 如何在 MVC 中显示 Asp.net 身份 cookie 过期弹出窗口

c# - Shaman.EPPlus + ASP.NET Core MVC - 部分已存在异常

asp.net-core - 使用 UseJwtBearerAuthentication 中间件自定义 401 和 403 响应模型