如何使用无密码连接字符串将 Visual Studio 中的 ASP.NET MVC 项目连接到 Azure SQL 数据库

问题描述 投票:0回答:1

我想找到一种利用 Azure 托管身份连接到 Azure SQL 数据库而无需密码的解决方案。

我已经根据以下文档在Azure上完成了设置。但是有两个问题。

https://learn.microsoft.com/en-us/samples/azure-samples/azure-sql-db-who-am-i/azure-sql-db-passwordless-connections/

  1. 我在 .NET 4.8 上使用 ASP.NET MVC,因此无法从解决方案复制代码。
  2. 我还想找到解决方案,一旦代码和设置完成,我确实想在本地测试连接。

这里有一些材料/代码,如果你也能给出一些解释,那就太好了。

asp.net-mvc azure-sql-database .net-4.8 azure-managed-identity
1个回答
3
投票

我在 Visual Studio 中创建了一个 ASP.NET MVC Web 应用程序。我在

appsetting.json
文件中给出的连接字符串为:

"ConnectionStrings": {
    "QuotesDatabase": "Server=tcp:<servename>.database.windows.net,1433; Database=<databasename>;" }

截图供参考:

enter image description here

我将以下包添加到项目中。

enter image description here

我添加了以下代码来连接到 Azure SQL 数据库:

var connectionString = Configuration.GetConnectionString("<connectionstringname>");
            services.AddTransient(a =>{
                var sqlConnection = new SqlConnection(connectionString);
                var credential = new DefaultAzureCredential();
                var token = credential
                        .GetToken(new Azure.Core.TokenRequestContext(
                            new[] { "https://database.windows.net/.default" }));
                sqlConnection.AccessToken = token.Token;
                return sqlConnection;

截图供参考:

enter image description here

我编写此查询是为了从 Azure SQL 数据库检索数据:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace SqlMSI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class QuotesController : ControllerBase
    {
        private readonly string connectionString;

        public QuotesController(SqlConnection dbconnection)
        {
            DbConnection = dbconnection;
        }

        public SqlConnection DbConnection { get; }
      
        public async Task<IActionResult> Get()
        {
            DbConnection.Open();
            var sqlCommand = new SqlCommand("select * from quote", DbConnection);
            var reader = sqlCommand.ExecuteReader();
            var quotes = new List<Quote>();

            while (reader.Read())
            {
                var quote = new Quote()
                {
                    Id = Guid.Parse(reader["Id"].ToString()),
                    QuoteNumber = int.Parse(reader["QuoteNumber"].ToString())
                };
                quotes.Add(quote);
            }

            return Ok(quotes);
        }
    }

    public class Quote
    {
        public Guid Id { get; set; }
        public int QuoteNumber { get; set; }
    }
}

截图供参考:

enter image description here

我设置 Azure 服务身份验证来检索令牌凭据。

截图供参考:

enter image description here

我将自己设置为 SQL Server 的管理员。

截图供参考:

enter image description here

我将客户端IP地址添加到sql服务器 图片供参考:

enter image description here

它成功运行并连接到azure sql数据库并从数据库检索数据。

参考图片:

enter image description here

我将项目发布到Azure应用程序服务中

参考图片: enter image description here

enter image description here

enter image description here

将azure中webapp的IP地址添加到sql服务器。

enter image description here

将系统分配的管理标识设置为 Azure 应用服务的状态。

enter image description here

我打开 SSMS 并使用活动目录密码选项登录服务器。

enter image description here

我使用以下代码创建了用户并向用户添加了角色

create user [quotes-app] from external provider;
alter role db_datareader add member [quotes-app];
alter role db_datawriter add member [quotes-app];

参考图片:

enter image description here

enter image description here

无需使用用户 ID 密码即可成功连接到应用程序。

参考图片:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.