c# - 似乎无法通过 ASP.Net Core 连接到 SQL Server(一直返回空值)

标签 c# angular asp.net-core sql-server-2016

我正在尝试通过配置管理器通过 n 层架构设计连接到我的本地 SQL Server。简而言之,我想从我的本地数据库查询数据,将它从 DataSet 序列化为 JSON,并以 JSON 格式读取它,以便我可以从我的 Angular 端收听它。

我通过在控制台应用程序中实现它来测试我的 n 层,结果是应该的,但是将那个确切的 n 层放入我的 ASP.NET Core 构建中并且它不断返回

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.

起初我实现了 web.config,因为我不知道 appsettings.json,但是当我试图通过 GET 从那个 json 文件调用 ConnectionString 时,它不断返回 null(可以是任何东西)。

在 BLL 类中,我尝试删除 Controller 继承,但没有显示任何值。

我还尝试了整个 Startup 方法,但是这需要太多依赖项。

文件夹结构:

Controller -> N-Tier -> DBConn;DAL;BLL;

应用设置.json

"ConnectionStrings": 
  { "Local_One": "Data source=localhost;Initial Catalog=VAS; User ID=user101; Password=password1;Trusted_Connection=True;MultipleActiveResultSets=true;" },


public class DBConn
{
    public string ConnectionString()
    {
        //Also where the error gets caught
        return ConfigurationManager.ConnectionStrings["Local_One"].ConnectionString;
    }
}

公共(public)类 DAL

public class DAL
{
    SqlConnection conn = new SqlConnection(new DBConn().ConnectionString());
    public string query = null;
    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
    int i = 0;

    public DataSet GetAllUserTypes()
    {
        if(conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }

        try
        {
            query = "sp_GETUSERTYPES"; //calls a stored procedure
            da.SelectCommand = new SqlCommand(query,conn);
            da.Fill(ds);
            ds.Tables[0].TableName = "USER TYPES";
            da.Dispose();
            conn.Close();
        }
        catch(SqlException e)
        {
        }

        return ds;
    }
}

公共(public)课BLL

[Produces("application/json")]
[Route("api/N-Tier/BLL/[action]")]//localhost:5000/api/N-Tier/BLL/GetAllUserTypes
public class BLL:Controller
{
    DAL dal = new DAL();

    public string GetAllUserTypes()
    {
        return JsonConvert.SerializeObject(dal.GetAllUserTypes(),Formatting.Indented);//using Newtonsoft.Json;
    }
}

预期结果(我从控制台 App.config 获得):

{
  "USERS": [
    {
      "userTypeID": 1,
      "userTypeDescription": "Registered_User"
    },
    {
      "userTypeID": 2,
      "userTypeDescription": "Administrator"
    },
    {
      "userTypeID": 3,
      "userTypeDescription": "Moderator"
    }
  ]
}

错误信息:

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.

最佳答案

在 asp.net Core 中,您不应该使用 ConfigurationManager 从 appsettings.json 获取,这就是您得到 null 的原因。相反:

在 Startup.cs 中

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
}

在您的 Controller 中为配置添加一个字段并在构造函数中为它添加一个参数

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
{
    configuration = config;
}

现在稍后在您的 View 代码中,您可以像这样访问它:

connectionString = configuration.GetConnectionString("Local_One");

Original source

关于c# - 似乎无法通过 ASP.Net Core 连接到 SQL Server(一直返回空值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501684/

相关文章:

c# - xamarin android中如何通过浏览打开文件夹并显示选中项的名称

Angular 2 & RxJs catch 函数回调绑定(bind)到 'this' 导致 http 请求一遍遍重复

html - 如何在 Angular2 中提供图像?

ios - Angular 2 数字键盘启动

c# - 在 Parallel.For 完成作业后引发事件

javascript - 使用javascript下载pdf文件内容

c# - 压缩图像,有什么意义吗?

azure-web-app-service - Azure 上的 Asp.Net VNext 应用程序设置

asp.net-core - IdentityServer4 Windows身份验证和ASP.Net Core MVC客户端 "Hello World"

c# - IdSrv4 - 访问 token 验证器端点