SumNone.com

Totally Nothing...Do-Dads and Fix-Its For the Web.

NAVIGATION - SEARCH

Easiest way to retrieve UserId as an Int with SimpleMembership ASP.NET MVC

I just spent hours trying to figure this, so I figured I'd write a little post on it to hopefully make life easier for someone else.  So, the goal was to select records from my table where the current logged in userid is equal to the userid in my table.  Simple, right?  I looked through many sites including those recommending to get the guid, some to convert, make another call to the db, session wrapper, etc..  All of these seem incredibly complex for what I want to do.  Why would I want a guid, when the user table isn't even a guid AND my table isn't a guid?  Both are ints, so why is this so hard and why would Microsoft convert it to a guid anyway when it's currently a single digit number?  This is also real easy if you want the username, but for some reason exponentially more difficult if you want the userid.  Turns out, it's not if you know what you're doing.

Anyway, the easiest way to do this is:

using WebMatrix.WebData;

using <your project name here>.Filters;

...

[InitializeSimpleMembership]

...

int uId = WebSecurity.GetUserId(User.Identity.Name);

or you may need to use in place of User.Identity.Name:

HttpContext.Current.User.Identity.Name

WebSecurity.GetUserId is part of WebMatrix.WebData.  I had come across the WebSecurity.GetUserId or WebSecurity.CurrentUserId a couple times (CurrentUserId will not work if I read the description correctly), but none tied it back to WebMatrix.WebData.

Keep in mind, my project thus far is pretty generic and based on the C# MVC4 Internet Project template.  The only thing I've added is a model, controller and some views to pull data from my table (all based on templates as well).

Good luck, I hope this solution finds you quicker than it did me.