c# - Asp.net 身份电子邮件验证不起作用

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

在我的网络应用程序中,我使用 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 格式发送用户信息问题是当用户电子邮件等于“example”或“example@example”时。或“example@example.com”

identityResult.成功返回false

但是当用户电子邮件等于“example@example”

identityResult.Succeeded 返回 true

我的问题是为什么电子邮件等于“example@example”

identityResult.Succeeded 返回 true?

最佳答案

查看 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@example.com 根据其逻辑不被视为有效的电子邮件地址。

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

关于c# - Asp.net 身份电子邮件验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863801/

相关文章:

javascript - 更改日期选择器中的日期

php - 如何将包含signalR的asp.net mvc页面与其他平台集成

jquery attr(readonly) 函数不起作用

asp.net-identity - ASP.NET Identity 中的安全 token 和安全标记是什么?

c# - AddScoped 服务不会在整个请求过程中保留设置

c# - Asp.net web 表单、Asp Identity - 如何存储来自 Facebook、Twitter 等的声明

c# - 有没有办法使用 Mage/MageUI 为 ClickOnce 应用程序 list 指定应用程序图标?

c# - 通过反射判断一个属性是否是一种数组

c# - 如何使我的 Web 项目中的链接图像出现在我的本地开发 Web 服务器上?

c# - 在打印前使用 WPF 窗口作为视觉模板