【问题标题】:.NET How to access the DBContext within OIDC Middleware.NET 如何在 OIDC 中间件中访问 DBContext
【发布时间】:2020-01-03 07:07:59
【问题描述】:

我有以下Startup.cs#ConfigureServices方法:

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => { Configuration.Bind("AzureAd", options); });

        //Register TracingContext to access the DB
        services.AddDbContext<TracingContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        });

        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
        {
            options.Events = new OpenIdConnectEvents
            {
                OnTokenValidated = ctx =>
                {
                    // Get the user's email 
                    var email = ctx.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

                    // Query the database to get the role
                    **// BUT: How do I access the TracingContext from above?** 
                    **// CODE HERE **

                    // Add claims
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Role, "HQUser")
                    };
                    var appIdentity = new ClaimsIdentity(claims);

                    ctx.Principal.AddIdentity(appIdentity);

                    return Task.CompletedTask;
                },
            };
        });
    }

由于我在方法中使用services.AddDbContext(...)定义了TracingContext (DBContext),如何才能访问OICD中间件中的TracingContext?

此时我需要从数据库中检索用户的角色。

谢谢

【问题讨论】:

  • TracingContext db = new TracingContext() 不工作?
  • 不,因为它需要 DbContextOptions 作为参数... public TracingContext(DbContextOptions options) : base(options)
  • 因此,如果您传入选项...,我的猜测是将 TracingContext 包装在另一个类中会更容易,然后使用 di 注入我相信您设置的选项在上面的行中。

标签: .net entity-framework asp.net-core dependency-injection .net-core


【解决方案1】:

你可以使用HttpContext.RequestServices.GetRequiredService来获取依赖:

var db = ctx.HttpContext.RequestServices.GetRequiredService<YourDbContext>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    相关资源
    最近更新 更多