[英]Successfully implementing custom UserManager<IUser> in Identity 2.0
我正在嘗試導航黑洞,這是身份成員身份的自定義實現。 我現在的目標只是從我的ApiController
獲取這一行來正確檢索我的UserManager:
public IHttpActionResult Index()
{
var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<MyUser,int>>();
//manager is null
}
這是我的設置。 在我的Startup
配置中,我設置了WebApi並添加了我的OwinContext:
app.CreatePerOwinContext<UserManager<MyUser,int>>(Create);
我的創建方法:
public static UserManager<User,int> Create(IdentityFactoryOptions<UserManager<MyUser,int>> options, IOwinContext context)
{
return new UserManager<MyUser,int>(new UserStore(new DbContext()));
}
其余的是我可以做的最基本的實現。
MYUSER:
public class MyUser : IUser<int>
{
public int Id { get; set; }
public string UserName { get; set; }
}
MyUserStore:
public class MyUserStore : IUserStore<MyUser,int>
{
private IdentityDbContext context;
public MyUserStore(IdentityDbContext c)
{
context = c;
}
//Create,Delete, etc implementations
}
MyDbContext:
public class MyDbContext : IdentityDbContext
{
public MyDbContext() : base("Conn")
{
}
}
這一切都是為了學習身份如何運作,我相信沒有人真正知道。 我希望能夠最終完全自定義我的用戶和角色,避免使用Microsoft的IdentityUser。
同樣,我現在的問題是在我的控制器中,我在嘗試檢索我的UserManager時變為null
。
非常感謝任何和所有的幫助。
我有幾個錯誤,但主要的是我的Startup類看起來像:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseWebApi(new WebApiConfig());
app.CreatePerOwinContext(MyDbContext.Create);
app.CreatePerOwinContext<MyUserManager>(MyUserManager.Create);
}
}
當然,OWIN管道將在觸發WebAPI調用后插入我的依賴項。 切換那些是我的主要問題。
此外,我終於在Google搜索中找到了這個很棒的指南 。 它幾乎可以回答我所得到的一切。 我需要實現一個UserManager<MyUser,int>
的具體類
我希望以后可以幫助別人。
您使用的是MyIdentity.User還是MyIdentity.MyUser? 在示例中,有兩個不同的對象傳遞給TUser參數。
我測試了您的實現,並且沒有檢索UserManager的已注冊實例的問題。
要完全自定義用戶和角色,您需要最終編寫UserManager的新實現,以便使您的身份驗證,聲明,角色,方法調用等工作。
如果您正在嘗試了解Identity的工作原理,我建議您使用UserManager和IdentityUser的默認實現。 讓它先工作。
最終,創建自己的用戶實現IdentityUser。 所有UserManager功能都可以使用,您將可以訪問新屬性。 其他屬性將自動構建到IdentityDbContext生成的AspnetUser表中。
public MyIdentityUser : IdentityUser
{
public int Id {get; set;}
public string CustomUserId {get; set;}
public string UserId { get; set; }
}
或者,您可以開始使用對其他對象的外鍵引用構建自定義MyIdentityUser。
public MyIdentityUser : IdentityUser
{
public virtual UserProperties Properties { get; set; }
}
這對你有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.