Question

Working with my project in debug I have no issues. However running it in IIS I am getting this error:

System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'.

Stack Trace

[SqlException (0x80131904): Login failed for user 'DOMAIN\NAME-PC$'.]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6749670
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +53
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6777754
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6778255
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +878
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1162
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +72
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +6781425
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +103
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2105
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1089
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6785863
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
   System.Data.SqlClient.SqlConnection.Open() +239
   System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) +65
   System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe() +38
   System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode() +30
   System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +81
   System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +54
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +446
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
   MvcMobile.Controllers.HomeController.Index() +38
   lambda_method(Closure , ControllerBase , Object[] ) +79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +261
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +34
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +124
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +839035
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +839620
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

The number one solution I can find through Google is to change the application pool advanced Identity settings which did not work.

I am using IIS 7.5 and I am connecting to SQLServer 2012 my connection string is below.

Connection String

<add name="_DataConnectionString" connectionString="Data Source=01DEV\SQLDEV01;Initial Catalog=_Data;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"
  providerName="System.Data.SqlClient" />
Was it helpful?

Solution 2

Assuming you're intending to use Windows Authentication to impersonate the service account, you have to set up Windows Authentication in both IIS and ASP.NET.

In IIS, make sure that the Windows Authentication module is added and enabled. Also make sure your application pool is running under a domain account, not a local account.

In ASP.NET make sure the authentication mode attribute is set to "Windows"

<system.web>
    <authentication mode="Windows"/>
</system.web>

OTHER TIPS

Just set Integrated Security=False and it will work ,according to a comment difference between True and False is:

True ignores User ID and Password if provided and uses those of the running process, SSPI(Security Support Provider Interface ) it will use them if provided which is why MS prefers this. They are equivalent in that they use the same security mechanism to authenticate but that is it.

I had similar experience and it took me time to solve the problem. Though, my own case was ASP.Net MVC Core and Core framework. Setting Trusted_Connection=False; solved my problem.

Inside appsettings.json file

"ConnectionStrings": {
    "DefaultConnection": "Server=servername; Database=databasename; User Id=userid; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true",
  },

You can also get this error if your SQL Server has not been configured to use Mixed mode authentication - it doesn't actually tell you that this is not enabled!

I faced the same situation. Create your connection string as follows.

Replace

"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"

by

"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"

add persist security info=True; in connection string.

I just ran into this error and it took days to resolve. We were thrown for a loop by the red-herring error message mentioned in the initial question, plus the Windows Event Viewer error log indicated something similar:

Login failed for user '(domain\name-PC)$'. Reason: Could not find a login matching the name provided. [CLIENT: <local machine>]

Neither of these was true, the user had all the necessary permissions in SQL Server.

In our case, the solution was to switch the Application Pool Identity in IIS to NetworkService.

kinda dumb, but I had a weird character (é) in my password. After omitting it, I no longer got the error.

I tried some of the suggested answers but it didn't resolve the issue. Finally I found out that the default connection timeout (not command timeout) is 15 seconds and once I increased it to 60 it almost never happened again. simply add this to you connection string: ;Connection Timeout=60 I chose 60 seconds but you can put any value you think would fit the best to your needs.

If your SQL Password has " in it, when authenticating and passing this password to authenticate it opens a String thereby not actually pushing your password to the application, but half your password and then opening a string!!! Very irritating :) but hope this helps some person.

@Chamila Maddumage this issue confusing me a long time, i was really under pressure. except the add the "Trusted_Connection=False;", i also need add a port number 1433 after the $SERVERNAME$DBinstanceName with a ',' like this "data source=XXXXXXX\SQLSERVER,1433;". i don't know why because it works fine before until a IT guy changed some settings to the SQL Server 2016.

BTW, my application was a desktop application not a Web application. And i also reference this link: error 26- error locating server/instance specified

http://www.windows-tech.info/15/9f6dedc097727100.php

Numpty here used SQL authentication

enter image description here

instead of Windows (correct)

enter image description here

when adding the login to SQL Server, which also gives you this error if you are using Windows auth.

Check the properties of SQL Sever from the Object explorer.

If Integrated Security is set to true, make the same changes in connection string as well.

check the screenshot of the property grid

It worked in case of ASP.NET Core Web Api...

I had this problem after I migrated a user profile from a Windows domain to Azure Active Directory (AzureAD), probably because my user name had changed, but my profile directory hadn't. I got around it by deleting %APPDATALOCAL%\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB.

If you are trying to connect to Local DB, note that IIS runs under a different user account; i.e., not the logged in user. To resolve the issue, there are two possible solutions:

  1. Add the existing user under the APPLICATION POOLS > [SELECT YOUR POOL] > ADVANCED SETTINGS > PROCESS MODEL -> IDENTITY = Custom account and set the account already added to SSMS > [YOUR SERVER] > Security > Logins > [SELECT THE NAME]

  2. Add a user under SSMS > [YOUR SERVER] > Security > Logins with limited rights and assign it under: APPLICATION POOLS > [SELECT YOUR POOL] > ADVANCED SETTINGS > PROCESS MODEL -> IDENTITY = Custom account and set the account

I have fixed this by disabling the "Enforce Password Expiration" option from SQL Server Management Studio -> Security -> Logins -> MyLoginUser'Properties

Recently I had experienced the same issue upon deployment, where the error was to do with the Windows Server User under IIS. As the hosting company only allowed connections via SQL Users.

I recommend that when anyone is in development via their IDE, for example, Visual Studio 2022 have set up a connection string in appsettings.json or for security reasons have it set up in User Secret and then access it via the code.

As I am using .Net 6 frameworks and I have a separate project for Migrations from the EF Core Class Library Project. In my Program.cs below the var builder = WebApplication.CreateBuilder(args);

I have added the following

IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

builder.Services.AddDbContext<DbEntities>(
            options =>
                options.UseSqlServer(
                    configuration.GetConnectionString("DevMsSqlConnection "),
                    x => x.MigrationsAssembly("EFCoreClassLibbaryName.Migrations")));

and in the appsettings.json file, I have added the following JSON format data to access Ms SQL Database in Development and then in the Production environment or if you are using MySQL Database I have added the Connection String for those too.

"ConnectionStrings": {
//Microsoft SQL Database Connection Strings

"DevMsSqlConnection": "Data Source=[Your Ms Sql Developer Database Server Name];Initial Catalog=[Your Ms Sql Development Database Name; Persist Security Info=True;User; Trusted_Connection=True",

"PrdMsSqlConnection": "Data Source=[Your Ms Sql Production Database Server Name];Initial Catalog=[Your Ms Sql Production Database Name];User ID=[Your Ms SQL Database User Name];Password=[Ms SQL Database User Password]; Trusted_Connection=False; MultipleActiveResultSets=true",

//MySQL Database Connection Strings
"DevMySqlConnection" :"server=[Your MySql Developer Database Server Name]; userid=[Your MySql Developer Database Server Username];password=[Your MySql Developer Database Server Password];database=[Your MySql Developer Database Name];persistsecurityinfo=True",

"PrdMySqlConnection" :"server=[Your MySql Production Database Server Name]; userid=[Your MySql Production Database Server Username];password=[Your MySql Production Database Server Password];database=[Your MySql Production Database Name];persistsecurityinfo=True",
},

For me, everything started working after I installed SSMS.

Not sure maybe it installed some libraries or something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top