asp.net核心中的连接字符串和应用设置

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

以前没有在.net内核中工作,并且连接字符串存在一些问题。我试图像这样在控制器中获取连接字符串

 SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DefaultConnection"].ToString());

但是我在控制器中得到了'对象引用未设置为对象的实例。'。这就是我的appsettings.json外观]]

"ConnectionStrings": {
    "DefaultConnection": "Server=(server)\\\\mssqllocaldb;Database=dbName;User ID=user;Password=123123"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

以前没有在.net内核中工作,并且连接字符串存在一些问题。我试图像我的控制器那样获取控制器中的连接字符串,所以SqlConnection conn = new SqlConnection(...

asp.net database asp.net-core exception connection-string
2个回答
2
投票

您无法直接在控制器中获取连接字符串,但是可以注入配置,然后可以在控制器中像这样访问连接字符串


0
投票

使用ConfigurationManager假定项目中存在“ App.config”,而不是appsettings.json。示例:

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