Apollo
Apollo

Reputation: 2070

Get Domain User ID in ASP.NET

I have a ASP.NET application where an employee logs into Windows and then they have to select their name from a long list of names and log in into the application.

What I want to do is as soon as the employee opens the application it selects their name from the drop down box.

I believe if I can get the Windows User Id on page load I can then make my code select the user depending on the Windows user that is logged in.

Question is. How do you get Windows User Id that is currently logged in in C# Asp.net? Any ideas.

Upvotes: 3

Views: 13565

Answers (3)

Sinji Yang
Sinji Yang

Reputation: 129

In ASP.NET Core .NET 6, I use

Environment.UserName;

// or // the following only work on Windows platform

System.Security.Principal.WindowsIdentity.GetCurrent().Name ;

Upvotes: -1

GoCowboys
GoCowboys

Reputation: 31

I was having an related issue where my local build was recognizing the WindowsIdentity.GetCurrent().Name.ToString() value as my Windows account name, but when I accessed the website via a server it was always "DefaultAppPool".

I was able to get this to work by doing the following:

  1. Open IIS and navigate to my website.
  2. Under the IIS sections, double click "Authentication".
  3. From there, disable "Anonymous Authentication" and "Forms Authentication".
  4. Enable "Windows Authentication".

From there I was able to discern the user id/name and proceed with my coding. I had to rework a little bit, but it was well worth it. Thanks for the advice!

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

Try this:-

System.Web.HttpContext.Current.User.Identity.Name

Also check this forum.

UPDATE:-

1) Please check that you have disabled anonymous mode in IIS

2) Also do check that you have set the application to autheticate the user details like this:-

 <authentication mode="Windows"/> 
    <authorization> 
       <allow users="*"/>
    </authorization>

or like this:-

  <authentication mode="Windows" /> 
     <authorization> 
        <deny users="?"/> 
     </authorization>

3) You can you can either configure IIS in Control Panel so that your site (or machine) uses Windows authentication and denies anonymous access

Upvotes: 9

Related Questions