![](/img/trans.png)
[英]How to connect to existing database? .NET Core API & SQL Server 2012
[英]How to connect an already existing .Net Core application to Azure SQL Database with managed identity
What are the steps to successfully connect the application to Azure SQL Database after setting up the connection string and adding the App Authentication NuGet package.
If you want to use Azure Managed Identity to connect Azure SQL database in.Net Core MVC project, We can use the package Microsoft.Data.SqlClient with SqlConnection.AccessToken.
詳細步驟如下。
創建微星
配置SQL數據庫
一個。 使用您的 Azure Sql AD 管理員連接 Azure Z9778840A01001B30C9828AiSSMSA47
灣。 將 MSI 添加到您需要使用的數據庫中
USE [<db name>] GO create user [<your msi name>] from external provider ALTER ROLE db_owner ADD MEMBER [<function app name>]
代碼
/*
Install SDK Microsoft.Azure.Services.AppAuthentication and Microsoft.Data.SqlClient
*/
public async Task<IActionResult> Index()
{
List<StarWar> starWars = new List<StarWar>();
var connectionString = "Server=tcp:<server-name>.database.windows.net,1433;Database=<database-name>;";
using (var conn = new SqlConnection(connectionString))
{
conn.AccessToken = await (new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/");
await conn.OpenAsync();
var sql = "SELECT * FROM [dbo].[StarWars]";
using (SqlCommand command = new SqlCommand(sql, conn))
{
using (SqlDataReader reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
StarWar starWar = new StarWar();
starWar.episode = Convert.ToInt32(reader["episode"]);
starWar.score = Convert.ToInt32(reader["score"]);
starWar.name = Convert.ToString(reader["name"]);
starWars.Add(starWar);
}
}
}
}
return View(starWars);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.