Search code examples
sql-serverasp.net-core

ASP.NET Core SQL Server connection string login failed for user


The following is my connection string

Server=MYDB01.somedomain.net;database=MYDB01;MultipleActiveResultSets=true;User ID=UserAdmin;Password=AdminPW;Integrated Security=True; Encrypt=True; TrustServerCertificate=True;Connection Timeout=60;

but when I attempt to try and connect to it in the C# ASP.NET code, I get an error

login failed for user MyNetwork/MyPcUserName

Why is it trying to use the user name on my computer, instead of the UserID and PW in the connectionstring? Or does this not matter and the problem is something else? I can connect to the DB using Microsoft SQL Server Management Studio, but not in my code

SqlConnection connection = new SqlConnection(connectionString);
connection.Open(); <-------- Login failed for user MyNetwork/MyPcUsername

Solution

  • Your connection string should have either a User ID and Password or Integrated Security set as True. They are two different methods of authentication. The User ID and Password is when you are using an SQL Server account to connect to the database. Integrated Security is when you are using your Windows login to connect to the database.

    So, for connecting with an SQL Server account:

    Server=MYDB01.somedomain.net;database=MYDB01;User ID=UserAdmin;Password=AdminPW;TrustServerCertificate=True;
    

    For connecting with Windows credentials:

    Server=MYDB01.somedomain.net;database=MYDB01;Integrated Security=True;TrustServerCertificate=True;
    

    Note that I removed other configurations in the connection string, which you only should set on an as-needed basis.