Search code examples
c#asp.net-mvcado.net

How to insert currently logged in username into a SQL table using ADO.NET (MVC 5)


I am writing a POST method in my controller that adds an item through a form in razor page. My table in MSSQL has a username column which indicates the currently loggedin user in Windows (i.e. jdoe). By that means, I want the username to be inserted in the table automatically every time a form is submitted, so that the db can keep track of who submitted which item. This is the snippet of the code in my function where I am trying to insert the current user:

cmd.Parameters.AddWithValue("@SUserName", ); //I don't know what to write to get and add the currently loggedin user

What should I do to INSERT the current username?


Solution

  • After hours of searches and helps from others, Environment.Username did my job.

    https://learn.microsoft.com/en-us/dotnet/api/system.environment.username?view=net-7.0