简体   繁体   English

注册用户asp.net身份模型错误

[英]Register user asp.net identity model error

I am creating a website using asp.net identity. 我正在使用asp.net身份创建一个网站。 I have created a data model based upon the default asp.net identity tables which is using the localdb. 我已经基于使用localdb的默认asp.net身份表创建了一个数据模型。 When I try to register a new user I get an error saying Bitev2.Models.AspNetUserLogin: : EntityType 'AspNetUserLogin' has no key defined. Define the key for this EntityType. AspNetUserLogins: EntityType: EntitySet 'AspNetUserLogins' is based on type 'AspNetUserLogin' that has no keys defined. 当我尝试注册一个新用户时,我得到一个错误,说Bitev2.Models.AspNetUserLogin: : EntityType 'AspNetUserLogin' has no key defined. Define the key for this EntityType. AspNetUserLogins: EntityType: EntitySet 'AspNetUserLogins' is based on type 'AspNetUserLogin' that has no keys defined. Bitev2.Models.AspNetUserLogin: : EntityType 'AspNetUserLogin' has no key defined. Define the key for this EntityType. AspNetUserLogins: EntityType: EntitySet 'AspNetUserLogins' is based on type 'AspNetUserLogin' that has no keys defined. However the AspNetUserLogin model is auto generated and contains no key. 但是,AspNetUserLogin模型是自动生成的,不包含任何密钥。

Any help would be greatly appreciated. 任何帮助将不胜感激。

AspNetUserLogin model AspNetUserLogin模型

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Bitev2.Models
{
    using System;
    using System.Collections.Generic;

    public partial class AspNetUserLogin
    {
        public string UserId { get; set; }
        public string LoginProvider { get; set; }
        public string ProviderKey { get; set; }

        public virtual AspNetUser AspNetUser { get; set; }
    }
}

AspNetLogins table/model AspNetLogins表/模型

AspNetLogins表/模型

As I said yesterday , Asp.Net Identity is something different! 正如我昨天所说 ,Asp.Net Identity是不同的东西!

I have created a data model based upon the default asp.net identity tables which is using the localdb. 我已经基于使用localdb的默认asp.net身份表创建了一个数据模型。

You don't need this step to register a new User. 您无需此步骤即可注册新用户。 The AspNetUserLogin table has an other purpose, the one consisting in saving external logins for the current user. AspNetUserLogin表有另一个用途,一个用于保存当前用户的外部登录。 So the user can login from Google, Facebook, etc. 因此用户可以从Google,Facebook等登录

To simply register a user, please drop AspNet**** tables from your model and write this code: 要简单注册用户,请从您的模型中删除AspNet****表并编写以下代码:

     //GET
    [AllowAnonymous]
    public ActionResult RegisterNewUser()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RegisterNewUser(RegisterNewUserViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                UserName = userViewModel.Email,
                Email = userViewModel.Email,
                EmailConfirmed =true
            };
            var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);

            //Add User to the Roles 
               string[] selectedRoles=new string[]{"Developer","Tester","Robbot"};
            if (adminresult.Succeeded)
            {
                if (selectedRoles != null)
                {
                    var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        return View();
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", adminresult.Errors.First());
                return View();

            }
            return RedirectToAction("Index");
        }
        return View();
    }

To use the AspNetUserLogin , You need two methods or steps: 要使用AspNetUserLogin ,您需要两个方法或步骤:

  • The First method is the one that will request a redirect to the external login provider ExternalLogin for example, and 第一种方法是请求重定向到外部登录提供程序ExternalLogin ,例如,和

  • The Second method/step you need is the one that will save the External Login in the AspNetUserLogin table. 您需要的第二个方法/步骤是将在AspNetUserLogin表中保存外部登录的方法/步骤。 this, without having this table generated in your model. 这样,没有在您的模型中生成此表。 Let's call this method ExternalLoginConfirmation . 我们将此方法称为ExternalLoginConfirmation

Need code? 需要代码?

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult ExternalLogin(string provider, string returnUrl)
    {
     return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
    }


    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Index", "Manage");
        }

        if (ModelState.IsValid)
        {
            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return View("ExternalLoginFailure");
            }
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
              //saving the External Login in the   `AspNetUserLogin` table
                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    return RedirectToLocal("local url here");
                }
            }

            foreach (var error in result.Errors)
            {
             ModelState.AddModelError("", error);
            }
        }

        ViewBag.ReturnUrl = returnUrl;
        return View(model);
    }

You'll need this class to! 你需要这门课!

    internal class ChallengeResult : HttpUnauthorizedResult
    {
        public ChallengeResult(string provider, string redirectUri)
            : this(provider, redirectUri, null)
        {
        }

        public ChallengeResult(string provider, string redirectUri, string userId)
        {
            LoginProvider = provider;
            RedirectUri = redirectUri;
            UserId = userId;
        }

        public string LoginProvider { get; set; }
        public string RedirectUri { get; set; }
        public string UserId { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
            if (UserId != null)
            {
                properties.Dictionary[XsrfKey] = UserId;
            }
            context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
        }
    }

If you need more information or if you are facing issue with missing types, see this post 如果您需要更多信息,或者如果您遇到缺少类型的问题, 请参阅此帖子

Hope this will help you... 希望这个能对您有所帮助...

Kind Regards! 亲切的问候!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM