我正在尝试自定义ASP Identity 2.0以使用Guid Key。 我可以登录 a-ok,但在尝试获取用户数据时遇到了一些问题。
这些都不起作用:
User.Identity.GetUserId()
[始终作为空字符串返回]
User.IsInRole("rolename")
[始终返回为假]
User.Identity.Name 已填充。
我的登录处理程序
public class CommandHandler : IRequestHandler<ViewModel, Result>
{
private readonly GuidUserManager _manager;
public CommandHandler(GuidUserManager manager)
{
_manager = manager;
}
public Result Handle(ViewModel criteria)
{
// Verify if a user exists with the provided identity information
var user = _manager.Find(criteria.UserName, criteria.Password);
// If a user was found
if (user == null)
return Result.Fail("Invalid username or password.");
// Clear any lingering authencation data
FormsAuthentication.SignOut();
// Write the authentication cookie
FormsAuthentication.SetAuthCookie(user.UserName, criteria.RememberMe);
return Result.Ok();
}
}
我的身份代码
using System;
using System.Data.Entity;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace FM.Web.Security
{
public class GuidUserDbContext : IdentityDbContext<GuidUser, GuidRole, Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
{
public GuidUserDbContext(string connection)
: base(connection)
{
Database.SetInitializer(new GuidUserDbContextInitialilser());
}
}
public class GuidUserDbContextInitialilser : CreateDatabaseIfNotExists<GuidUserDbContext>
{
}
public class GuidUserManager : UserManager<GuidUser, Guid>
{
public GuidUserManager(GuidUserStore userStore)
: base(userStore)
{
}
}
public class GuidUserLogin : IdentityUserLogin<Guid>
{
}
public class GuidUserRole : IdentityUserRole<Guid>
{
}
public class GuidUserClaim : IdentityUserClaim<Guid>
{
}
public class GuidRole : IdentityRole<Guid, GuidUserRole>
{
}
public class GuidUserStore : UserStore<GuidUser, GuidRole, Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
{
public GuidUserStore(DbContext context)
: base(context)
{
}
}
public class GuidRoleStore : RoleStore<GuidRole, Guid, GuidUserRole>
{
public GuidRoleStore(DbContext context)
: base(context)
{
}
}
public class GuidUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
{
}
}
您需要在帐户控制器中使用此代码
public GuidUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<GuidUserManager>();
}
private set
{
_userManager = value;
}
}
FormsAuthentication
是你的问题。可能您的web.config
包含与MembershipRoleProvider
相关的条目 - 弄乱User.IsInRole
.删除与表单身份验证相关的所有代码/配置以解决您的问题。
另请参阅此答案