162
  • How can I get the id of the currently logged in user in MVC 5? I tried the StackOverflow suggestions, but they seem to be not for MVC 5.
  • Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a User should have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?

I'm using "Individual User Accounts" from the MVC template.

Tried these:

'Membership.GetUser()' is null.

Community
  • 1
  • 1
Adam Szabo
  • 11,302
  • 18
  • 64
  • 100
  • Added the references of what I've tried. The last one was OK in MVC4 but not in MVC5. Also I need some best practice of "using User" :) – Adam Szabo Aug 26 '13 at 16:38
  • When you say you are using MVC 5, what are you using for membership? OWin.Security? – Aron Aug 26 '13 at 16:40
  • "Individual User Accounts" from the MVC template. – Adam Szabo Aug 26 '13 at 16:42
  • 3
    `HttpContext.Current.User.Identity.Name` is the name of currently logged user. – Wiktor Zychla Aug 26 '13 at 18:01
  • 1
    How to get the **Id**? I would like to assign the current user to the `Item` he creates, but not based on the username (that might change). It's not working by the way ` HttpContext.Current 'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found (are you missing a using directive or an assembly reference?)`. Are you sure your solution is for MVC 5? – Adam Szabo Aug 26 '13 at 18:09
  • Hey so I managed to get it with User.Identity.GetUserId(), you can get an idea of how they use it on the login partial view of a sample project that uses asp.net's Identity. Any doubts just let me know, by the way the id is a huge string. – oskar132 Oct 15 '13 at 00:48
  • oskar132, thanks, I solved it way back, details in my own answer. It also mentions that the user ID is a GUID stored as a string. – Adam Szabo Oct 16 '13 at 08:05
  • I always make people sign up in my software with their email address and keep track of them with that. Their email is always unique and the ball is then in their court and their email provider. I then make sure my application is ready so that if they need to change their email address it will be a simple process to do so. It's not rocket science, it's just a little bit trickier! – Bojangles May 30 '14 at 10:59

9 Answers9

321

If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

If you're in a class other than a Controller, use

HttpContext.Current.User.Identity.GetUserId();

In the default template of MVC 5, user ID is a GUID stored as a string.

No best practice yet, but found some valuable info on extending the user profile:

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
Adam Szabo
  • 11,302
  • 18
  • 64
  • 100
  • 10
    User authentication and authorization have changed for ASP.NET MVC 5. Now it's a Claims-based authentication with interfaces and generic repositories that you can use with EF or other provider (EF implementation comes as a default). Since `GetUserId` is an extension method stored at the bottom of `Ass_Start\IdentityConfig.cs`, wherever you need to use it, if on a diferent namespace, you'll have to set the `using Microsoft.AspNet.Identity` for the extension to become visible. – Anderson Matos Sep 26 '13 at 22:16
  • 1
    survey.UserId = Guid.Parse(User.Identity.GetUserId()); – NicoJuicy Nov 13 '13 at 22:45
  • If I add the using reference User is still underlined red? Why would this be? – Zapnologica Jan 31 '14 at 08:44
  • @Zapnologica: try to rebuild the project, maybe VS IntelliSense is a bit slow. – Adam Szabo Jan 31 '14 at 09:33
  • GetUserId disappearance was what I stumbled into. thanks – Vahid Ghadiri Jan 31 '14 at 19:24
  • 5
    NOTE User is only available in a Controller http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.user(v=vs.118).aspx (@Zapnologica are you using it outside of a controller? try HttpContext.Current.User.Identity.GetUserId();) – Adween May 30 '14 at 08:59
  • `HttpContext` is also only defined within the controller. – Isaac Kleinman Oct 31 '14 at 15:06
  • GetUserId(); returns null for me. Anyone know why? – andre de waard Mar 10 '15 at 11:18
  • As of 2015 RC1 the GetUserId extension method is in the System.Security.Claims namespace – matt. Jul 11 '15 at 23:29
  • How to get the user details by passing token? Can we do like this? – Jeeva J Sep 23 '15 at 05:12
  • Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. This was my problem Thanks! :) – Samra Jul 25 '17 at 02:11
28

Try something like:

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

Works with RTM.

Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327
Rok Bermež
  • 365
  • 3
  • 3
  • 11
    It imposes unnecessary database trip. – Arash Feb 15 '14 at 12:43
  • 3
    @Arash, how is the application supposed to get the user's object without contacting the database? – fabspro Mar 08 '14 at 07:29
  • 2
    @Arash never mind, I see what you mean. The ID can be retrieved with User.Identity.GetUserId(); without any database trip. – fabspro Mar 08 '14 at 07:38
  • Remember with mvc5 (membership 2): User.Identity.GetUserId() is different with id in table [AspNetUsers]. So Jakub Arnold and Rok is correct way – Wolf Sep 26 '14 at 07:18
  • I'm a bit confused with the answer. I'm getting a UserStore type doesn't seem to exist in my controller context. Any ideas? – Jhourlad Estrella Oct 20 '15 at 16:20
  • Totally wrong approach. There is another issue with this code. UserManager is instantiated once per one owin context. there is no need to instantiate it again every time you need it. just get it from owincontext. – Manoochehr Dadashi Nov 26 '15 at 13:07
19

If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You'll need the following using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
firecape
  • 726
  • 6
  • 10
7

Getting the Id is pretty straight forward and you've solved that.

Your second question though is a little more involved.

So, this is all prerelease stuff right now, but the common problem you're facing is where you're extending the user with new properties ( or an Items collection in you're question).

Out of the box you'll get a file called IdentityModel under the Models folder (at the time of writing). In there you have a couple of classes; ApplicationUser and ApplicationDbContext. To add your collection of Items you'll want to modify the ApplicationUser class, just like you would if this were a normal class you were using with Entity Framework. In fact, if you take a quick look under the hood you'll find that all the identity related classes (User, Role etc...) are just POCOs now with the appropriate data annotations so they play nice with EF6.

Next, you'll need to make some changes to the AccountController constructor so that it knows to use your DbContext.

public AccountController()
{
    IdentityManager = new AuthenticationIdentityManager(
    new IdentityStore(new ApplicationDbContext()));
}

Now getting the whole user object for your logged in user is a little esoteric to be honest.

    var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
    .FindAsync(User.Identity.GetUserId(), CancellationToken.None);

That line will get the job done and you'll be able to access userWithItems.Items like you want.

HTH

EightyOne Unite
  • 11,665
  • 14
  • 79
  • 105
  • I don't suppose there is anything like pre-release docs for all this is there? – Derek Tomes Oct 16 '13 at 01:16
  • @Derek Tomes - Not that I've come across. I reckon we'll have to wait until Nov 13 for real docs. It's not been great to be honest, there's even a request for better guidance over at uservoice - http://aspnet.uservoice.com/forums/41199-general-asp-net/suggestions/4148568-better-guidance-documentation-on-mvc-5 – EightyOne Unite Oct 16 '13 at 18:04
  • ok but how do I get to an instance of type `AccountController`? – nest Aug 13 '15 at 17:43
0

I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.

I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication and set the filterContext.HttpContext.User to null

That's the best I've managed to far...

public abstract class ApplicationController : Controller   
{
    ...
    protected override void OnAuthentication(AuthenticationContext filterContext)
    {
        base.OnAuthentication(filterContext); 

        if ( ... )
        {
            // You may find that modifying the 
            // filterContext.HttpContext.User 
            // here works as desired. 
            // In my case I just set it to null
            filterContext.HttpContext.User = null;
        }
    }
    ...
}
Derek Tomes
  • 3,989
  • 3
  • 27
  • 41
0
        string userName="";
        string userId = "";
        int uid = 0;
        if (HttpContext.Current != null && HttpContext.Current.User != null
                  && HttpContext.Current.User.Identity.Name != null)
        {
            userName = HttpContext.Current.User.Identity.Name;              
        }
        using (DevEntities context = new DevEntities())
        {

              uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
            return uid;
        }

        return uid;
Hari Lakkakula
  • 199
  • 1
  • 4
  • Please do not just post code especially not without any comments. If you explain your code it would be more helpful. – Ali Kanat Feb 08 '19 at 09:52
0

if anyone else has this situation: i am creating an email verification to log in to my app so my users arent signed in yet, however i used the below to check for an email entered on the login which is a variation of @firecape solution

 ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);

you will also need the following:

using Microsoft.AspNet.Identity;

and

using Microsoft.AspNet.Identity.Owin;
Duan Walker
  • 305
  • 1
  • 11
0

In .Net MVC5 core 2.2, I use HttpContext.User.Identity.Name . It worked for me.

Bhupinder Yadav
  • 346
  • 3
  • 8
0

This is how I got an AspNetUser Id and displayed it on my home page

I placed the following code in my HomeController Index() method

ViewBag.userId = User.Identity.GetUserId();

In the view page just call

ViewBag.userId 

Run the project and you will be able to see your userId