【问题标题】:How to specify a username using connection string in Entity Framework如何在实体框架中使用连接字符串指定用户名
【发布时间】:2019-07-17 11:06:15
【问题描述】:

我的 ASP.Net Core 应用程序一直尝试使用“默认”用户名登录数据库,即使我在我正在使用的连接字符串中指定了不同的用户。那就是我不断收到同样的异常:

处理请求时发生未处理的异常。 SqlException:无法打开登录请求的数据库“testDB”。登录失败。 用户“DESKTOP-555DDD\skorejen”登录失败

即使我使用的连接字符串定义了不同的用户名。

如何修复它,以便我的应用使用连接字符串指定的用户名登录?

连接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=testDB;User Id=myusername;Trusted_Connection=True;"
  },

ASP.Net Core Startup.cs 文件:

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

【问题讨论】:

  • 使用 Tructed Connection 时,使用经过身份验证的 Windows 用户 的凭据;用户名和密码选项将被忽略。您需要让应用程序在适当的 AD 帐户下运行(通过模拟),将使用应用程序的用户添加到有效登录名(使用 AD 组可能更容易,而不是添加他们的每个登录名)或改用 SQL 身份验证。

标签: c# sql-server entity-framework asp.net-core


【解决方案1】:

您的ConnectionStrings 必须采用以下格式:

使用凭据(SQL 身份验证):

"ConnectionStrings": {
  "DefaultConnection": "Server=myServerAddress; Database=myDataBase; User Id=myUsername; Password=myPassword; Trusted_Connection=false; MultipleActiveResultSets=true;"
}

无凭据(Windows 身份验证):

"ConnectionStrings": {       
  "DefaultConnection": "Server=myServerAddress; Database=myDataBase; Trusted_Connection=True; MultipleActiveResultSets=true"        
} 

【讨论】:

    【解决方案2】:

    您需要启用sql authentication mode,将用户添加到 sql server 登录并在连接字符串中指定密码。

    示例连接字符串:

    服务器=myServerAddress;Database=myDataBase;用户 ID=myUsername; 密码=我的密码;

    (source)

    启用sql authentication mode:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2014-07-17
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多