无法在dotnet core web api(sql server)中连接数据库

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

我正在研究.NETCore 2 Web API。我开始使用连接字符串在本地数据库上工作,如下面的代码片段所示:

public void ConfigureServices(IServiceCollection services)
{

  services.AddCors(options => options.AddPolicy("Cors", builder =>
  {
    builder
      .AllowAnyOrigin()
      .AllowAnyMethod()
      .AllowAnyHeader();
  }));

  services.AddMvc();

  var connection = @"Server=.;Database=ESociety;Trusted_Connection=True;";
  services.AddDbContext<ESocietyContext>(options => options.UseSqlServer(connection));
  services.AddScoped<IArtistRepository, ArtistRepository>();
}

它工作正常。

然后我更改为数据库连接字符串以指向smarterasp服务器。我可以通过SSMS连接到smarterasp服务器上的数据库。

但我无法通过Web API连接。

public void ConfigureServices(IServiceCollection services)
{

  services.AddCors(options => options.AddPolicy("Cors", builder =>
  {
    builder
      .AllowAnyOrigin()
      .AllowAnyMethod()
      .AllowAnyHeader();
  }));

  services.AddMvc();

  var connection = @"Server=sql6***.site4now.net;Database=[dbname];Trusted_Connection=True;User Id=[username];password=[password]";
  services.AddDbContext<ESocietyContext>(options => options.UseSqlServer(connection));
  services.AddScoped<IArtistRepository, ArtistRepository>();
}

我错过了什么或者我创建的连接字符串不正确吗?

提前致谢。

.net-core asp.net-core-webapi
1个回答
0
投票

您应该从连接字符串中删除此部分

Trusted_Connection=True

或者它将尝试使用您的Windows凭据连接到数据库。

所以工作字符串应该是

@"Server=sql6***.site4now.net;Database=[dbname];User Id=[username];password=[password]"

你可以在这里阅读有关差异:

https://www.connectionstrings.com/sql-server/

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