将连接字符串移动到appsettings.json

时间:2018-12-01 16:11:09

标签: c# asp.net-core dao

我有以下DAO代码:

using Dapper;
using PerformanceComWebAPI.Modelos;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

namespace PerformanceComWebAPICompleto.DAO
{
    public class ClienteDAO
    {
        //string da conexão com a base de dados
        private const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TesteDapper;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        /// <summary>
        /// Listar todos os cliente da base de dados
        /// </summary>
        /// <returns></returns>
        public List<Cliente> Listar()
        {
            var sql = "select * from dbo.Cliente";
            List<Cliente> clientes = new List<Cliente>();

            using (var connection = new SqlConnection(connectionString))
            {
                clientes = connection.Query<Cliente>(sql).ToList();
            }

            return clientes;
        }

        /// <summary>
        /// Metodo que recupera o cliente pelo id
        /// </summary>
        /// <param name="idCliente">id cliente que vai ser recuperado</param>
        /// <returns>O cliente que correspondente do cliente ou null quando não tiver cliente com id</returns>
        public Cliente RecuperarPorID(int idCliente)
        {
            var sql = "select * from dbo.Cliente where id = @id";

            Cliente cliente = new Cliente();

            using (var connection = new SqlConnection(connectionString))
            {
                cliente = connection.QueryFirstOrDefault<Cliente>(sql, new { id = idCliente });
            }

            return cliente;
        }
    }
}

我想知道如何从此页面移动连接字符串并将其插入到appsettings.json文件中,以便可以在其他页面上重复使用。

1 个答案:

答案 0 :(得分:0)

在ASP.NET Core中,配置系统非常灵活,并且连接字符串可以存储在appsettings.json,环境变量,用户密码存储或其他配置源中。有关更多详细信息,请参见Configuration section of the ASP.NET Core documentation。以下示例显示了存储在appsettings.json中的连接字符串。

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

通常在Startup.cs中配置上下文,并从配置中读取连接字符串。请注意,GetConnectionString()方法将查找键为ConnectionStrings:<connection string name>的配置值。您需要导入Microsoft.Extensions.Configuration命名空间才能使用此扩展方法。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}