Name cannot be null or empty. asp.net identity mvc

2019-03-25 19:24发布

问题:

Has anyone had a problem with this. He throws me the error: Name can not be null or empty. But in the table do not have the attribute called "Name". I want to customize Asp.Net Identity.

Controller

  public class HomeController : Controller
{
    //
    // GET: /Home/
    public async Task<ActionResult> Index()
    {
        var userStore = new UserStore<User,Identity_2Context.MyRole,long,Identity_2Context.MyUserLogin,Identity_2Context.MyUserRole,Identity_2Context.MyClaim>(new Identity_2Context());
        var manager = new UserManager<User,long>(userStore);

        var user = new User()
        {
            UserName = "TehnoMac",Email = "TehnoMac@tehcno.com",IsApproved = true,IsLockedOut = false,
            CreatedDate = DateTime.Now,LastActivityDate = DateTime.Now,LastLoginDate = DateTime.Now,FailedPasswordAnswerAttemptCount = 0,
            FailedPasswordAttemptCount = 0
        };

        var result = await manager.CreateAsync(user, "test123test");

        if (result.Succeeded)
        {
            var authenticationManager = HttpContext.GetOwinContext().Authentication;
            var userIdentity = manager.Create(user, DefaultAuthenticationTypes.ApplicationCookie);
        }
        else
        {
            ViewBag.Text = result.Errors.FirstOrDefault();
        }

        return View();
    }
}

IdentityModel public class ApplicationUser : IdentityUser { }

public class MyClaim:IdentityUserClaim<long>
{
}

public class MyRole:IdentityRole<long,MyUserRole>
{
}

public class MyUserRole:IdentityUserRole<long>
{
}
public class MyUserLogin:IdentityUserLogin<long>
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser,MyRole,long,MyUserLogin,MyUserRole,MyClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}

回答1:

Make sure you have specified a username. I got the same error and after setting the UserName property, the error went away.



回答2:

Solved (for me at least) By REMOVING the UserName property from the customized identity (its in the GitHub ASPNetIdentitySample project which is where I guess people are getting it from). Its hiding the UserName property in IdentityUser