首页 > 解决方案 > 如何将 Azure MSI AccessToken 添加到 EF6 DbContext 以连接 Azure SQL PaaS

问题描述

使用 MVC 和 EF6 代码优先方法,我能够集成 Azure MSI 令牌并执行 CRUD 操作,但是如何执行迁移,我必须将令牌注入 DBContext:

连接字符串: 在此处输入图像描述

对于执行 CRUD 查询,我使用如下遗留的 ADO.NET 样式查询,它可以工作: 在此处输入图像描述

获取 MSI: 在此处输入图像描述 为了运行迁移,如何将 Azure MSI AccessToken 传递给 DbContext 构造函数。 在此处输入图像描述

对于 dbcontext 我必须用提供者名称定义单独的连接字符串。 在此处输入图像描述

标签: c#azureentity-framework

解决方案


您需要在 DI 中进行设置:

启动.cs

    public void ConfigureServices(IServiceCollection services)
    {
        //code ignored for simplicity
        services.AddDbContext<AzureProvider>();

        services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
    }

数据库上下文

public partial class AzureProvider: DbContext
{
    public IConfiguration Configuration { get; }
    public IDBAuthTokenService authTokenService { get; set; }

    public AzureProvider(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<AzureProvider> options)
        : base(options)
    {
        Configuration = configuration;
        authTokenService = tokenService;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
        connection.AccessToken = authTokenService.GetToken().Result;

        optionsBuilder.UseSqlServer(connection);
    }
}


public class AzureSqlAuthTokenService : IDBAuthTokenService
{
    public async Task<string> GetToken()
    {
        AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
        var token = await provider.GetAccessTokenAsync("https://database.windows.net/");

        return token;
    }
}

使用托管标识与 Azure SQL 的 EF Core 连接


推荐阅读