gpt4 book ai didi

c# - EF Core 通过托管标识连接到 Azure SQL

转载 作者:行者123 更新时间:2023-12-03 14:17:26 24 4
gpt4 key购买 nike

我正在使用 EF Core 连接到部署到 Azure 应用服务的 Azure SQL 数据库。我正在使用访问 token (通过托管身份获得)连接到 Azure SQL 数据库。

这是我的做法:

启动.cs:

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

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

MyCustomDBContext.cs
public partial class MyCustomDBContext : DbContext
{
public IConfiguration Configuration { get; }
public IDBAuthTokenService authTokenService { get; set; }

public CortexContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<MyCustomDBContext> 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);
}
}

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

return token;
}
}

这工作正常,我可以从数据库中获取数据。但我不确定这是否是正确的方法。

我的问题:
  • 这是正确的方法还是会出现性能问题?
  • 我需要担心 token 过期吗?我现在没有缓存 token 。
  • EF Core 有没有更好的方法来处理这个问题?
  • 最佳答案

    Is this a right way to do it or will it have issues with performance?



    那是正确的方法。每个新的 DbContext 都会调用 OnConfiguring,因此假设您没有任何长期存在的 DbContext 实例,这是正确的模式。

    Do I need to worry about token expiration? I am not caching the token as of now.


    AzureServiceTokenProvider负责缓存。

    Does EF Core has any better way to handle this?



    设置 SqlConnection.AccessToken 是目前在 SqlClient for .NET Core 中使用 AAD 身份验证的唯一方法。

    关于c# - EF Core 通过托管标识连接到 Azure SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187241/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com