名称不能为null或为空:_userManager.CreateAsync

时间:2017-10-03 19:51:49

标签: c# asp.net asp.net-web-api asp.net-authentication

我收到此错误:

  

名称不能为空或空

在进行POST调用时

https://localhost:44346/api/account/register。 _userManager.CreateAsync由于某种原因不喜欢它。

我的代码:

UserModel.cs类:

public class UserModel : IdentityUser
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

AccountController.cs:

// POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await _repo.RegisterUser(userModel);

            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return errorResult;
            }

            return Ok();
        }

实现RegisterUser的AuthRepository类:

private AuthContext _ctx;

        private UserManager<UserModel> _userManager;

        public AuthRepository()
        {
            _ctx = new AuthContext();
            _userManager = new UserManager<UserModel>(new UserStore<UserModel>(_ctx));
        }
public async Task<IdentityResult> RegisterUser(UserModel userModel)
        {
            UserModel user = new UserModel
            {
                UserName = userModel.UserName
            };

            try
            {
                var result = await _userManager.CreateAsync(user, userModel.Password);

                return result;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

        }

我不明白为什么我会收到此错误&#34;名称不能为空&#34;当我明确指定它时。

到目前为止我尝试了什么: 1.在UserModel.cs中添加新属性Name 2.按照Name cannot be null or empty. asp.net identity mvc 5 + EntityFreamwork中的建议从UserModel类中删除UserName,但这给了我一个不同的异常(UserModel在上下文中不存在)。

我正在尝试按照此处的建议实施OAuth:http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/ 他的源代码:https://github.com/tjoudeh/AngularJSAuthentication

请帮忙。

编辑:由于某种原因,我看到2个UserName属性,其中1个为null。这就是我看到错误的原因吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

使用ADO.NET连接字符串而不是EntityFramework 1,此问题将自行解决。

相关问题