How to get current user who's accessing an ASP.NET application?
If you're using membership you can do: Membership.GetUser()
Your code is returning the Windows account which is assigned with ASP.NET.
Additional Info Edit:
You will want to include System.Web.Security
using System.Web.Security
Getting The Current User Name In ASP.NET Application
Try using this to retrieve the username....
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
string username = System.Web.HttpContext.Current.User.Identity.Name;
}
It sounds like windows authentication is not being used - you need to disable anonymous access and enable windows integrated security.
Add this to your web.config...
<system.web>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
How to get the current user in ASP.NET MVC
If you need to get the user from within the controller, use the User
property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData
, or you could just call User as I think it's a property of ViewPage
.
Get current windows user who is accessing an ASP.NET Core Application
That's not how you do it. What you're doing returns the principal the application is running under. Locally, that's obviously you, because it's running under your account. However, on the server, it's the App Pool user. In either case, it's not the user accessing the application; it was only coincidental that locally, the user accessing the application and the account the application is running under were the same.
What you're looking for is Windows Authentication, which you need to specifically turn on (see: Configure Windows Authentication in ASP.NET Core). Then, you access the user as you would always access the user, regardless of authentication scheme: HttpContext.User
.
How to get current user in asp.net core
User.FindFirst(ClaimTypes.NameIdentifier).Value
EDIT for constructor
Below code works:
public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}
Edit for RTM
You should register IHttpContextAccessor
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}
ASP.NET Core Identity - get current user
If your code is inside an MVC controller:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
From the Controller
base class, you can get the ClaimsPrincipal
from the User
property
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
You can check the claims directly (without a round trip to the database):
bool isAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:
Other fields can be fetched from the database's User entity:
Get the user manager using dependency injection
private UserManager<ApplicationUser> _userManager;
//class constructor
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}And use it:
var user = await _userManager.GetUserAsync(User);
var email = user.Email;
If your code is a service class, you can use dependency injection to get an IHttpContextAccessor
that lets you get the User
from the HttpContext.
private IHttpContextAccessor _httpContextAccessor;
public MyClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private void DoSomething()
{
var user = _httpContextAccessor.Context?.User;
}
How to get the current logged in user ID in ASP.NET Core?
I included using System.Security.Claims and I could access the GetUserId() extension method
NB: I had the using Microsoft.AspNet.Identity already but couldn't get the extension method. So I guess both of them have to be used in conjunction with one another
using Microsoft.AspNet.Identity;
using System.Security.Claims;
EDIT:
This answer is now outdated. Look at Soren's or Adrien's answer for a dated way of achieving this in CORE 1.0
How do I get the current username in .NET using C#?
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
ASP.NET MVC 5 - Identity. How to get current ApplicationUser
You should not need to query the database directly for the current ApplicationUser.
That introduces a new dependency of having an extra context for starters, but going forward the user database tables change (3 times in the past 2 years) but the API is consistent. For example the users
table is now called AspNetUsers
in Identity Framework, and the names of several primary key fields kept changing, so the code in several answers will no longer work as-is.
Another problem is that the underlying OWIN access to the database will use a separate context, so changes from separate SQL access can produce invalid results (e.g. not seeing changes made to the database). Again the solution is to work with the supplied API and not try to work-around it.
The correct way to access the current user object in ASP.Net identity (as at this date) is:
var user = UserManager.FindById(User.Identity.GetUserId());
or, if you have an async action, something like:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
FindById
requires you have the following using statement so that the non-async UserManager
methods are available (they are extension methods for UserManager, so if you do not include this you will only see FindByIdAsync
):
using Microsoft.AspNet.Identity;
If you are not in a controller at all (e.g. you are using IOC injection), then the user id is retrieved in full from:
System.Web.HttpContext.Current.User.Identity.GetUserId();
If you are not in the standard Account controller you will need to add the following (as an example) to your controller:
1. Add these two properties:
/// <summary>
/// Application DB context
/// </summary>
protected ApplicationDbContext ApplicationDbContext { get; set; }
/// <summary>
/// User manager - attached to application DB context
/// </summary>
protected UserManager<ApplicationUser> UserManager { get; set; }
2. Add this in the Controller's constructor:
this.ApplicationDbContext = new ApplicationDbContext();
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
Update March 2015
Note: The most recent update to Identity framework changes one of the underlying classes used for authentication. You can now access it from the Owin Context of the current HttpContent.
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
Addendum:
When using EF and Identity Framework with Azure, over a remote database connection (e.g. local host testing to Azure database), you can randomly hit the dreaded “error: 19 - Physical connection is not usable”. As the cause is buried away inside Identity Framework, where you cannot add retries (or what appears to be a missing .Include(x->someTable)
), you need to implement a custom SqlAzureExecutionStrategy
in your project.
Related Topics
Date Difference in Years Using C#
Serilog Mssql Sink Doesn't Write Logs to Database
Httpcontext.Current.Session Is Null in Ashx File
Why C# Won't Allow Field Initializer with Non-Static Fields
Simulating Keyboard with Sendinput API in Directinput Applications
Are Ienumerable Linq Methods Thread-Safe
Creating an Mvvm Friendly Dialog Strategy
How to Enable Nullable Reference Types Feature of C# 8.0 for the Whole Project
Linq: Passing Lambda Expression as Parameter to Be Executed and Returned by Method
Why Is List When Passed Without Ref to a Function Acting Like Passed with Ref