Search code examples
asp.net-mvc-3linqmembership

How to retrieve user Id from membership database in asp.net mvc3?


I've created a database with reg_sql and added it to my project database for membersip. Now I need to access to loged in user Id. In very simple way I want to show it in a view to see doesitwrk or not. I use this code in a function in my contoller:

  var id = from ad in StoreDb.aspnet_Users where
  StoreDb.aspnet_Users.Name == System.Web.HttpContext.Current.User.Identity.Name 
  select ad.UserId;
  ViewBag.Message = id;

But in view I saw this:

System.Data.Objects.ObjectQuery`1[System.Guid]

What shoud I do to retrieve User Id??? Thanks


Solution

  • Here's a function you can drop into your controller and use it in an action to get the ID. It isn't necessary to do all that code to query the membership database when the provider gives you an API to do all that already.

    private Guid GetUserID() {
        var currentUser = Membership.GetUser(User.Identity.Name);
        var userID = (Guid)currentUser.ProviderUserKey;
        return userID;
    }
    
    public ActionResult Index() {
        var userID = GetUserID();
        ...
    }
    

    You could also put that code into a base controller so you could access that function from any controller that inherits from it. That keeps your code DRY (dont' repeat yourself) so you don't have code duplication

    Usage would be

    Create a base controller and put in a folder under Controllers called Base

    namespace YourApp.Web.Controllers {
        public abstract class MyBaseController : Controller {
    
            protected Guid GetUserID() {
                var currentUser = Membership.GetUser(User.Identity.Name);
                var userID = (Guid)currentUser.ProviderUserKey;
                return userID;
            }
        }
    }
    

    Now you can use that base controller in any of your regular controllers by inheriting from it.

    public class HomeController : MyBaseController {
    
        public ActionResult Index() {
            var userID = GetUserID();
            ...
        }
    }