Custom Membership with Microsoft.AspNet.Identity - CreateLocalUser fails

后端 未结 3 629
傲寒
傲寒 2021-01-30 14:43

I\'ve been trying to implement a custom version of the new Identity features in ASP.NET 4.5 (Microsoft.AspNet.Identity), using Visual Studio 2013. After many hours of playing a

3条回答
  •  情话喂你
    2021-01-30 15:25

    The issue here is that IdentityStoreManager has strong dependency on the default implementation of identity EF models. For example, the CreateLocalUser method will create UserSecret and UserLogin objects and save them to stores, which won't work if the store is not using the default model type. So if you customize the model type, it won't work smoothly with IdentityStoreManager.

    Since you only customize the IUser model, I simplified the code to inherit custom user from default identity user and reuse other models from identity EF models.

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    
    namespace WebApplication11.Models
    {
        public class PulseUser : User
        {
            public PulseUser() { }
            public PulseUser(string userName) : base(userName)
            {
            }
    
            [StringLength(100)]
            public string Email { get; set; }
            [Column(TypeName = "Date")]
            public DateTime? BirthDate { get; set; }
            [StringLength(1)]
            public string Gender { get; set; }
        }
    
        public class PulseUserContext : IdentityStoreContext
        {
            public PulseUserContext(DbContext db) : base(db)
            {
                this.Users = new UserStore(this.DbContext);
            }
        }
    
        public class PulseDbContext : IdentityDbContext
        {
        }
    }
    

    The code above should work with preview version of Identity API.

    The IdentityStoreManager API in upcoming release is already aware of this issue and changed all the non-EF dependency code into a base class so that you can customize it by inheriting from it. It should solve all the problems here. Thanks.

提交回复
热议问题