Asp.net mvc 在mvc5中获取LoginUserId
我用过这个方法Asp.net mvc 在mvc5中获取LoginUserId,asp.net-mvc,asp.net-mvc-5,Asp.net Mvc,Asp.net Mvc 5,我用过这个方法 using Microsoft.AspNet.Identity; var currentUser = User.Identity.GetUserId(); 但我得到的错误对象引用未设置为对象的实例 我也无法获得mvc4中的Web安全性和登录用户id。这是我的一个代码片段中的一个示例,其中我使用1 DbContext来管理Identity和Model first类 如果尚未扩展您的IdentityUser模型,则可以使用此方法检索用户ID: //Id in Identi
using Microsoft.AspNet.Identity;
var currentUser = User.Identity.GetUserId();
但我得到的错误对象引用未设置为对象的实例
我也无法获得mvc4中的Web安全性和登录用户id。这是我的一个代码片段中的一个示例,其中我使用1 DbContext来管理Identity和Model first类
如果尚未扩展您的IdentityUser
模型,则可以使用此方法检索用户ID:
//Id in Identity is Guid; returning as string for simplicity
public string GetUserId(string username)
{
var um = new UserManager<IdentityUser>(
new UserStore<IdentityUser>(
new IdentityDbContext()));
return um.FindByName(username).Id;
}
。。。您需要相应地更改上述代码
var um = new UserManager<CustomUserModel>(
new UserStore<CustomUserModel>(
new IdentityDbContext()));
var um=new UserManager(
新用户商店(
新的IdentityDbContext());
IdentityDbContext
也是如此,它是您的DbContext类
希望这有帮助。这解决了我的问题
var LoginuserId=User.Identity.GetUserId();
使用下面的代码可能会对您有所帮助
public ImportFormFromExcelController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public ImportFormFromExcelController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public Guid getLoginUserInfoId()
{
Guid loginUserInfoId = new Guid();
string loginUserId = User.Identity.GetUserId();
var searchLoginUserInfoId = from m in db.UserInfos
where
m.UserID == loginUserId
select m;
foreach (var c in searchLoginUserInfoId)
{
loginUserInfoId = c.UserInfoID;
}
return loginUserInfoId;
}
.GetUserId()
是自定义方法吗?我没有可用的,所以应该找到错误there@Serv使用Microsoft.AspNet.Identity;当我在其他方法中以字符串um=GetUserId重新运行userid时;我收到错误,无法将方法组“getuserid”转换为非委托类型stringI我不理解。我希望在控制器的其他方法中调用登录用户id,在该方法中,它获取登录用户id并将其值发送到其他表。这完全是另一个问题,不是您上面描述的问题的一部分。这是唯一的问题我需要登录用户id的原因
public ImportFormFromExcelController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public ImportFormFromExcelController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public Guid getLoginUserInfoId()
{
Guid loginUserInfoId = new Guid();
string loginUserId = User.Identity.GetUserId();
var searchLoginUserInfoId = from m in db.UserInfos
where
m.UserID == loginUserId
select m;
foreach (var c in searchLoginUserInfoId)
{
loginUserInfoId = c.UserInfoID;
}
return loginUserInfoId;
}
Guid loginUserInfoId = getLoginUserInfoId();