Search code examples
asp.net-mvc-3authenticationuserid

How to get the userID of a logged in user?


I'm trying to get the userid of the currently logged in user. Here is my code:

public int GetUserID(string _UserName)
    {
        using (var context = new TourBlogEntities1())
        {
            var UserID = from s in context.UserInfoes
                         where s.UserName == _UserName
                         select s.UserID;
            return  Int32.Parse(UserID.ToString()); //error is showing here

        }
    }

I'm calling the method from my controller using this:

public ActionResult NewPost(NewPost model)
   {
       var Business = new Business();
       var entity = new Post();
       entity.PostTitle = model.PostTitle;
       entity.PostStory = model.PostStory;
       entity.UserID = Business.GetUserID(User.Identity.Name);



       Business.NewPost(entity);
       Business.ViewPost(entity);
       return View("ViewPost", model);

   }

The error is showing as "input string is not in correct format". Please help. Thanks.


Solution

  • Your query returns an IEnumerable. You need to get only the single record:

    using (var context = new TourBlogEntities1())
    {
        var userIds = from s in context.UserInfoes
                     where s.UserName == _UserName
                     select s.UserID;
        return userIds.Single();
    }
    

    By the way the .Single() method will throw an exception if there are more than 1 records matching the criteria. Hopefully you have an unique constraint on the Username field inside your database.