Login failed for user 'MACHINE\ASPNET'Cannot open database "xxx" requested by the login. The login failed.A network-related or instance-specific error occurred while establishing a connection to SQL Server.ASP.NET 應用程式預設以 ASPNET(IIS 6)或 NETWORK SERVICE / ApplicationPoolIdentity(IIS 7+)帳號執行。若連接字串使用 Integrated Security=SSPI(Windows 驗證),SQL Server 必須授權該 Windows 帳號登入並存取目標資料庫。
開啟 SQL Server Management Studio,選擇 Windows Authentication 連線至目標執行個體。
-- 取代 YOUR_MACHINE_NAME 為實際電腦名稱
EXEC sp_grantlogin 'YOUR_MACHINE_NAME\ASPNET'; -- IIS 6
-- 或
EXEC sp_grantlogin 'NT AUTHORITY\NETWORK SERVICE'; -- IIS 7+ 預設
-- 或應用程式集區身分識別
EXEC sp_grantlogin 'IIS APPPOOL\YourAppPoolName';
USE YourDatabaseName;
EXEC sp_grantdbaccess 'YOUR_MACHINE_NAME\ASPNET'; -- 或對應帳號
-- 簡單做法:加入 db_owner(開發/測試環境)
EXEC sp_addrolemember 'db_owner', 'YOUR_MACHINE_NAME\ASPNET';
-- 生產環境建議:僅給必要權限
EXEC sp_addrolemember 'db_datareader', 'YOUR_MACHINE_NAME\ASPNET';
EXEC sp_addrolemember 'db_datawriter', 'YOUR_MACHINE_NAME\ASPNET';
-- 若需執行預存程序
GRANT EXECUTE ON SCHEMA::dbo TO 'YOUR_MACHINE_NAME\ASPNET';
若不想管理 Windows 帳號,可改用 SQL 登入:
<connectionStrings>
<add name="ConnStr" connectionString="
Server=.;Database=YourDB;User Id=aspnet_user;Password=StrongPwd;
TrustServerCertificate=True" />
</connectionStrings>
若應用程式需以特定網域使用者身分存取 SQL:
<system.web>
<identity impersonate="true" userName="DOMAIN\user" password="pwd" />
</system.web>
連接字串維持 Integrated Security=SSPI,SQL Server 授權該網域使用者即可。
| 項目 | 正確範例 | 錯誤範例 |
|---|---|---|
| Server | Server=.\SQLEXPRESS | Server=127.0.0.1\SQLEXPRESS(若未啟用 TCP/IP) |
| Database | Database=MyDB | Initial Catalog=MyDB(兩者皆可) |
| Integrated Security | Integrated Security=SSPI | Integrated Security=True(同義) |
| TrustServerCertificate | TrustServerCertificate=True(本地測試) | 缺少導致 TLS 驗證失敗 |
Audit Login Failed 事件,確認失敗帳號與錯誤代碼。tnc DB_SERVER -Port 1433。ApplicationPoolIdentity 或自訂帳號。aspnet_regiis -pef connectionStrings 加密 web.config 區段。Max Pool Size=100; Min Pool Size=5 依負載調整。sys.dm_exec_sessions 觀察連接池使用狀況。