这更多的是一种异步电动机/等待问题比ASP.NET身份。 我使用Asp.Net身份,并有一个自定义UserStore,用定制的GetRolesAsync方法。 该的UserManager从控制器的WebAPI叫。
public class MyWebApiController {
private MyUserManager manager = new MyUserManager(new MyUserStore());
[HttpGet]
public async Task<bool> MyWebApiMethod(int x) {
IList<string> roles = await manager.GetRolesAsync(x);
return true;
}
}
public class MyUserManager : UserManager<MyUser, int> {
// I do not implement a custom GetRolesAsync in the UserManager, but
// from looking at the identity source, this is what the base class is doing:
// public virtual async Task<IList<string>> GetRolesAsync(TKey userId)
// {
// ThrowIfDisposed();
// var userRoleStore = GetUserRoleStore();
// var user = await FindByIdAsync(userId).WithCurrentCulture();
// if (user == null)
// {
// throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,userId));
// }
// return await userRoleStore.GetRolesAsync(user).WithCurrentCulture();
// }
}
public class MyUserStore {
public async Task<IList<string>> GetRolesAsync(TUser user) {
// I need HttpContext here and it is NULL. WHY??
var currentContext = System.Web.HttpContext.Current; // NULL!
var query = from userRole in _userRoles
where userRole.UserId.Equals(userId)
join role in _roleStore.DbEntitySet on userRole.RoleId equals role.Id
select role.Name;
return await query.ToListAsync();
}
}
为什么是空的上下文中MyUserStore.GetRolesAsync? 我想伺机传递的上下文下来? 我已经通过在MyUserStore其他异步方法,加强与它们都具有正确的上下文,代码似乎几乎相同。