.net core 3 中间件或授权属性?以及如何?

.net core 3 middleware or authorization attribute ? and how to?

我在

我有一个多数据库项目。用户在登录表单中从列表中选择一个数据库。之后我在 "selectedDb" 声明

中设置了 dbName/connectionString

在每个控制器中,我有 8 到 20 个 类(管理器)需要 DbContext 作为参数构造函数 => 我无法在控制器构造函数中创建管理器或 dbContext 的实例,因为我没有登录令牌还没有!

因此,在每个 Action 中,我都会创建一个 dbContext 实例(令牌提供连接字符串)和管理器实例...但这意味着我必须 "copy/paste" 在每个实例中使用相同的 3/4 代码行动作

如何提供数据库上下文的有效实例?可能使用中间件或自定义授权属性

有什么方法可以在控制器构造函数中创建 dbcontext 的实例吗? (令牌提供 "dynamic connection string")

一些代码示例

初始化类函数(避免每次复制16&3#92行)

private DatabaseContext InitContextAndManager(string connectionString)
{
    _dbContext = new DatabaseContext(connectionString);

    _someManager1 = new SomeManager_1(_dbContext);
    _someManager2 = new SomeManager_2(_dbContext);
    _someManager3 = new SomeManager_3(_dbContext);
    _someManager4 = new SomeManager_4(_dbContext);
    _someManager5 = new SomeManager_5(_dbContext);
    _someManager6 = new SomeManager_6(_dbContext);
    _someManager7 = new SomeManager_7(_dbContext);
    _someManager8 = new SomeManager_8(_dbContext);
    _someManager9 = new SomeManager_9(_dbContext);
    _someManager10 = new SomeManager_10(_dbContext);
    _someManager11 = new SomeManager_11(_dbContext);
    _someManager12 = new SomeManager_12(_dbContext);
    _someManager13 = new SomeManager_13(_dbContext);
    _someManager14 = new SomeManager_14(_dbContext);
    _someManager15 = new SomeManager_15(_dbContext);
}

一些Api例子

[Authorize]
public ActionResult Api_1()
{
    var connectionString = User.Identity.GetConnectionString();
    InitContextAndManager(connectionString);

    //some api_1 stuff
}

[Authorize]
public ActionResult Api_2()
{
    var connectionString = User.Identity.GetConnectionString();
    InitContextAndManager(connectionString);

    //some api_2 stuff
}

[Authorize]
public ActionResult Api_3()
{
    var connectionString = User.Identity.GetConnectionString();
    InitContextAndManager(connectionString);

    //some api_3 stuff
}

在@Ruard van Elburg 的帮助下

这里是解决方案

public ControllerConstructor(DbConnectionInfo db)
{
    _databaseContext = db.DbContext;
    _someManager1 = new SomeManager(_dbcontext);
}
public class DbConnectionInfo
{
    public DatabaseContext DbContext { get; set; }

    public DbConnectionInfo(IHttpContextAccessor httpContextAccessor)
    {
        var user = httpContextAccessor.HttpContext.User;
        //for question example
        DbContext = new DatabaseContext(user.Identity.GetConnectionString);
    }
}
[Authorize]
public ActionResult Api_1()
{
    //some api_1 stuff
}