c# - 如何将 Azure MSI AccessToken 添加到 EF6 DbContext 以连接 Azure SQL PaaS
问题描述
使用 MVC 和 EF6 代码优先方法,我能够集成 Azure MSI 令牌并执行 CRUD 操作,但是如何执行迁移,我必须将令牌注入 DBContext:
对于执行 CRUD 查询,我使用如下遗留的 ADO.NET 样式查询,它可以工作:
获取 MSI: 为了运行迁移,如何将 Azure MSI AccessToken 传递给 DbContext 构造函数。
解决方案
您需要在 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;
}
}
推荐阅读
- python - 您将如何做到这一点,以便可以根据 python 中的另一个名称列表重新分配数据框列表
- java - 检查 ElementCollection 映射是否有匹配的条目
- c++ - Windows 上来自 VS C++ 的非法指令
- c# - 尝试在列表中打印值给了我“Project.Game”
- snowflake-cloud-data-platform - 我可以从 Snowflake 接口中的 SnowSql 会话中查找查询 ID 吗?
- xcode - 找不到 RCTPushNotification.xcodeproj
- jenkins - 如何通过 Jenkins 声明式管道脚本加载 Groovy 文件并在其中调用方法
- c# - .NET MVC 路由在菜单控制器上重定向到特定控制器
- linux - 想知道我是否可以在它执行时应用加载,这可能吗?
- java - 我怎样才能通过列表
进入可变参数方法