[c#] System.Data.SqlClient.SqlException: Login failed for user

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" />

This question is related to c# iis sql-server-2012 connection-string

The answer is


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",
  },

add persist security info=True; in connection string.


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!


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


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"

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.


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.


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...


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.


Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with iis tag:

ASP.NET Core 1.0 on IIS error 502.5 CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default Publish to IIS, setting Environment Variable IIS Manager in Windows 10 The page cannot be displayed because an internal server error has occurred on server The service cannot accept control messages at this time NuGet: 'X' already has a dependency defined for 'Y' Changing project port number in Visual Studio 2013 System.Data.SqlClient.SqlException: Login failed for user "This operation requires IIS integrated pipeline mode." Difference between IISRESET and IIS Stop-Start command Accessing a local website from another computer inside the local network in IIS 7 Visual Studio breakpoints not being hit IIS w3svc error Installed SSL certificate in certificate store, but it's not in IIS certificate list The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security HTTP Error 500.19 and error code : 0x80070021 IIS: Idle Timeout vs Recycle HTTP Error 503. The service is unavailable. App pool stops on accessing website Why is HttpContext.Current null? How to create a self-signed certificate for a domain name for development? IIS - 401.3 - Unauthorized HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory Could not load file or assembly "Oracle.DataAccess" or one of its dependencies IIS error, Unable to start debugging on the webserver "Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) Specified argument was out of the range of valid values. Parameter name: site HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp Access-control-allow-origin with multiple domains ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d Unable to launch the IIS Express Web server Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel IIS: Display all sites and bindings in PowerShell IIS_IUSRS and IUSR permissions in IIS8 IIS - can't access page by ip address instead of localhost HTTP Error 503, the service is unavailable 401 Unauthorized: Access is denied due to invalid credentials Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list Error - Unable to access the IIS metabase How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode? Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS IIS 7, HttpHandler and HTTP Error 500.21 Dots in URL causes 404 with ASP.NET mvc and IIS Cannot serve WCF services in IIS on Windows 8 MVC4 HTTP Error 403.14 - Forbidden MIME types missing in IIS 7 for ASP.NET - 404.17 "401 Unauthorized" on a directory ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8 The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Questions with sql-server-2012 tag:

Count the Number of Tables in a SQL Server Database SQL Server IF EXISTS THEN 1 ELSE 2 Get last 30 day records from today date in SQL Server No process is on the other end of the pipe (SQL Server 2012) How to subtract 30 days from the current date using SQL Server Possible to restore a backup of SQL Server 2014 on SQL Server 2012? SQL Server: Best way to concatenate multiple columns? SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN' SSIS Excel Connection Manager failed to Connect to the Source Sql server - log is full due to ACTIVE_TRANSACTION Index was outside the bounds of the Array. (Microsoft.SqlServer.smo) SQL Server IIF vs CASE System.Data.SqlClient.SqlException: Login failed for user Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0 Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs How to automatically generate unique id in SQL like UID12345678? How to restore a SQL Server 2012 database to SQL Server 2008 R2? The server principal is not able to access the database under the current security context in SQL Server MS 2012 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions Insert Multiple Rows Into Temp Table With SQL Server 2012 Cannot execute script: Insufficient memory to continue the execution of the program Cannot Resolve Collation Conflict Correct way to select from two tables in SQL Server with no common field to join on Convert Date format into DD/MMM/YYYY format in SQL Server Cannot connect to SQL Server named instance from another SQL Server How can I use LTRIM/RTRIM to search and replace leading/trailing spaces? Recover unsaved SQL query scripts How to enable bulk permission in SQL Server SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry Last executed queries for a specific database New Line Issue when copying data from SQL Server 2012 to Excel SQL Server 2012 Install or add Full-text search How can I tell if a VARCHAR variable contains a substring? "No backupset selected to be restored" SQL Server 2012 Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update SQL Server 2012 can't start because of a login failure Enable remote connections for SQL Server Express 2012 Auto increment primary key in SQL Server Management Studio 2012 How do I import a .bak file into Microsoft SQL Server 2012? What is the connection string for localdb for version 11 Where is SQL Server Management Studio 2012? SQL Server Configuration Manager not found Insert/Update/Delete with function in SQL Server Find Locked Table in SQL Server How to check if a column exists in a SQL Server table?

Questions with connection-string tag:

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App How to read connection string in .NET Core? Connect to SQL Server Database from PowerShell System.Data.SqlClient.SqlException: Login failed for user Entity Framework change connection at runtime A network-related or instance-specific error occurred while establishing a connection to SQL Server How can I set an SQL Server connection string? VB.NET Connection string (Web.Config, App.Config) Connection string using Windows Authentication How to find SQL Server running port? error: the details of the application error from being viewed remotely What is the connection string for localdb for version 11 How to fix error ::Format of the initialization string does not conform to specification starting at index 0:: How to increase time in web.config for executing sql query Should I set max pool size in database connection string? What happens if I don't? Keyword not supported: "data source" initializing Entity Framework Context Get connection string from App.config Entity Framework Timeouts Read connection string from web.config Setting up connection string in ASP.NET to SQL SERVER SQL providerName in web.config How should I edit an Entity Framework connection string? Java JDBC - How to connect to Oracle using Service Name instead of SID Escape quote in web.config connection string SSIS how to set connection string dynamically from a config file Login failed for user 'NT AUTHORITY\NETWORK SERVICE' What is the point of "Initial Catalog" in a SQL Server connection string? Create a jTDS connection string What is the MySQL JDBC driver connection string? keyword not supported data source What is the difference between Integrated Security = True and Integrated Security = SSPI? How to fix "The ConnectionString property has not been initialized" Error: "Could Not Find Installable ISAM"