Asp.net mvc 3 如何获取登录用户的用户ID?
我正在尝试获取当前登录用户的用户ID。这是我的密码:Asp.net mvc 3 如何获取登录用户的用户ID?,asp.net-mvc-3,authentication,userid,Asp.net Mvc 3,Authentication,Userid,我正在尝试获取当前登录用户的用户ID。这是我的密码: public int GetUserID(string _UserName) { using (var context = new TourBlogEntities1()) { var UserID = from s in context.UserInfoes where s.UserName == _UserName
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
}
}
我正在使用以下命令从控制器调用该方法:
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);
}
错误显示为“输入字符串格式不正确”。请帮忙。谢谢。您的查询返回一个IEnumerable。您只需要获得一条记录:
using (var context = new TourBlogEntities1())
{
var userIds = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return userIds.Single();
}
顺便说一下,
.Single()
方法将在有多条记录与条件匹配时引发异常。希望您在数据库中的用户名字段上有一个独特的约束。谢谢,伙计……也许是时候回到基础上来了!是的,是时候开始做最基本的事情了。LINQ是本例中的基础。在进入ASP.NETMVC之前,您可能应该先学习它。我学了一点,但现在我肯定会再看一看。谢谢
CreatedBy = this.HttpContext.User.Identity.Name,