Tuesday, March 31, 2009

System.Data.SqlClient.SqlException: Login failed for user 'MachineName\ASPNET'

        Yesterday I was trying to deploy my ASP.Net website in the IIS for my another application to refer.
        After successfully deployed in IIS when I ran the application I got an error saying Login failed for...
        Pretty much after struggling a lot time I came to know that I need to add ASPNET user in my Database user's list.
        But when I tried to add the user in the SQL management studio ( SQL Express ) it failed.
        Finally I got the solution from a website to add the ASPNET user account for SQL from a command prompt command. I thought sharing this will help.
        You need to execute the SQL to add ASPNET as a login to your DB and setup their DA permissions, etc. (use VS Command Prompt) So launch "osql -S . -E" then
        paste in this SQL and it should start working for you; don't forget to put GO as the last statement when executing in the command prompt.
        
        exec sp_grantlogin N'THOR\ASPNET'
        exec sp_defaultdb N'THOR\ASPNET', N'pubs'
        exec pubs
        exec sp_grantdbaccess N'THOR\ASPNET', N'ASPNET'
        exec sp_addrolemember N'db_owner', N'ASPNET'
        
        
        Replace THOR with your machine name and replace pubs with your database name. One note is that this SQL adds ASPNET as dbo, so the ASPNET user has total control over that DB. This is the fastest way to get it working, but I'd suggest doing some research on SqlServer DB security to know how to scale back the permissions for this user.

        
        Note: Make sure you had run the aspnet_regiis command in the Visual Studio Command Prompt