【发布时间】:2014-08-25 09:48:41
【问题描述】:
我从 VS2013 中 ASP.net 的默认模板开始。我想获取当前的用户对象。这应该可以在不直接访问数据库的情况下实现。
应该是这样的
var currentUser = manager.FindById(User.Identity.GetUserId());
但是 FindById 不见了!几个小时以来,我一直在尝试改用 FindByIdAsync。但我想我遇到了死锁。
public class UserManager : UserManager<IdentityUser>
{
public UserManager()
: base(new UserStore<IdentityUser>(new ApplicationDbContext()))
{
}
public async System.Threading.Tasks.Task<IdentityUser> GetCurrentUser()
{
var user = await FindByIdAsync(HttpContext.Current.User.Identity.Name);
return user;
}
}
调用属性:
private IdentityUser_CurrentUser;
protected IdentityUser CurrentUser
{
get
{
if (_CurrentUser == null)
{
var manager = new UserManager();
var result = manager.GetCurrentUser();
//-- STOPS HERE!!
_CurrentUser = result.Result;
}
return _CurrentUser;
}
}
任何帮助将不胜感激!要么告诉我 FindById 去了哪里,要么如何让我的代码工作。还是有另一种加载 IdentityUser 的方法?
添加
在用户管理器中,没有找到FindById,但是找到了this.FindById。我将添加屏幕截图。这不是一个合适的解决方案,因为我不明白为什么会这样,或者有人可以解释这种行为吗?我附加了 2 个打开智能感知的屏幕。我还想提一下,这不是智能感知的问题——如果我不添加this.,代码将无法编译
智能感知输入“Fi”:
.
智能感知输入“this.Fi”:
这样,至少我不再卡住了。
【问题讨论】:
-
不确定这是否相关,但
class UserManager : UserManager<IdentityUser>总是让我感到困惑。为什么不class MyUserManager : UserManager<IdentityUser>? -
什么类的调用属性?您是否直接从控制器尝试过代码,并将管理器实例化为
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context));,然后使用 FindByIdAsync。见鬼,UserManager 怎么能知道诸如 HttpContext 之类的想法??? -
class MyUserManager : UserManager
取自教程asp.net/web-forms/tutorials/aspnet-45/…。到目前为止,它一直运行良好。 -
我认为我的块与此有关:blog.stephencleary.com/2012/07/dont-block-on-async-code.html 但是将我的整个母版页标记为异步只是为了读取用户对象对我来说似乎不合适。
-
我想你找到了问题所在。我只是补充一点,最新的 ASP MVC(官方)模板在 AccountController 中使用
async方法,而该方法使用await。
标签: c# asp.net webforms asp.net-identity