Asp.net身份电子邮件验证无效

时间:2016-04-26 11:36:19

标签: c# asp.net asp.net-identity

在我的Web应用程序中,我使用asp.net身份来管理用户 这是我注册用户的注册方法

   [AllowAnonymous]
    public async Task<IHttpActionResult> Register(UserRegisterJson userRegisterJson)
    {
        IUserManagement userManagement = new UserManagement();
        var user = userManagement.GetUserFromJson(userRegisterJson);

        var identityResult = await UserManager.CreateAsync(user, userRegisterJson.Password);

        if (!identityResult.Succeeded)
        {
            //return error
        }else{
            return Ok(true);
        }


    }

我在请求正文中以json格式发送用户信息问题是当用户电子邮件等于&#34;示例&#34;或&#34;示例@ example。&#34;或者&#34;例如@ exam ple.com&#34;

identityResult.Succeeded返回false

但是当用户的电子邮件等于&#34;示例@ example&#34;

identityResult.Succeeded返回true

我的问题是为什么电子邮件等于&#34;示例@ example&#34;

identityResult.Succeeded返回true?

1 个答案:

答案 0 :(得分:0)

查看source code of UserValidator for that verison (v2.2.1),在UserManager.CreateAsync旁边调用了以下方法。

// make sure email is not empty, valid, and unique
private async Task ValidateEmailAsync(TUser user, List<string> errors)
{
    var email = await Manager.GetEmailStore().GetEmailAsync(user).WithCurrentCulture();
    if (string.IsNullOrWhiteSpace(email))
    {
        errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PropertyTooShort, "Email"));
        return;
    }
    try
    {
        var m = new MailAddress(email);
    }
    catch (FormatException)
    {
        errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.InvalidEmail, email));
        return;
    }
    var owner = await Manager.FindByEmailAsync(email).WithCurrentCulture();
    if (owner != null && !EqualityComparer<TKey>.Default.Equals(owner.Id, user.Id))
    {
        errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateEmail, email));
    }
}

正如您所看到的,它正在尝试使用提供的电子邮件地址创建MailAddress对象。如果地址格式不正确,则应该失败。

考虑到他们使用的格式,我创建了一个单元测试来验证您提供的示例。

[DataDrivenTestMethod]
[DataRow("example")]
[DataRow("example@example.")]
[DataRow("example@exam ple.com")]
[DataRow("example@example")]
public void ValidateEmailAddress(string email) {
    var m = new System.Net.Mail.MailAddress(email);
    Assert.IsNotNull(m);
}

返回以下结果

Result Message: 
Assert.IsTrue failed. 

DataRow: email: example
Summary: Exception has been thrown by the target of an invocation.

DataRow: email: example@exam ple.com
Summary: Exception has been thrown by the target of an invocation.

exampleexample@exam ple.com根据其逻辑不被视为有效的电子邮件地址。

我建议您在创建新用户之前尝试在模型上执行自己的电子邮件验证