使用 EmailAddressAttribute 在 .net 中验证电子邮件字符串,但不在属性上

Validating an email string in .net using EmailAddressAttribute, but not on an attribute

我希望能够做到这一点:

string email = "some@email.com";
bool isValid = IsValidEmail(email);
//returns true

...但是使用 Microsoft 已经在 EmailAddressAttribute.

中给我们的逻辑

IsValidEmail 有数百种好的和坏的实现,我不想添加我自己的,当我可以使用某些东西时,Microsoft 已经考虑过了。按理说,他们会比我做得更好。

在最近的 ASP.Net 版本中,我们有 System.ComponentModel.DataAnnotations,它为我们提供了出色的 EmailAddressAttribute,让我们可以像这样装饰我们的模型:

public class SomeModel
{
    [EmailAddress]
    public string Email { get; set; }
}

class is sealed,所以我不能调用EmailAddressAttribute.IsValid()

有什么好的方法可以利用 Microsoft 已经完成的工作吗? .Net 框架中是否有某种方法可以让我根据数据注释测试字符串,我忽略了?

类似...的内容:

var emailChecker = new DataAnnotationsChecker<EmailAddressAttribute>();
string email = "some@email.com";
bool isValid = emailChecker.IsValid(email);
//returns true

如果你无法想象我为什么要这个,考虑获取一个列表并想检查哪些是有效的电子邮件。

您可以使用 EmailAddressAttribute 进行验证。

sealed 意味着您不能创建另一个继承它的 class。并不代表你不能使用它。

创建了一些单元测试并且工作正常

[TestMethod]
public void Should_Use_Email_Address_Attribute_To_Validate_Email() {
    var emailChecker = new System.ComponentModel.DataAnnotations.EmailAddressAttribute();
    string email = "some@email.com";
    bool isValid = emailChecker.IsValid(email);
    Assert.IsTrue(isValid);
}

[TestMethod]
public void Should_Use_Email_Address_Attribute_To_Invalidate_Email() {
    var emailChecker = new System.ComponentModel.DataAnnotations.EmailAddressAttribute();
    string email = "some@emai l.com";
    bool isValid = emailChecker.IsValid(email);
    Assert.IsFalse(isValid);
}

使用邮件地址
这是一种用于阅读和验证电子邮件地址的有用技术,即使是来自“Elmer Fudd ”样式的输入(例如那些复制-从电子邮件客户端粘贴)。

private string? ExtractEmailAddress(string raw)
{
    try
    {
        var address = new MailAddress(raw);
        return address.Address;
    }
    catch (Exception)
    {
        return null;
    }
}

我还使用 [EmailAddress] 属性来指示 API 文档所需的类型。

EmailAddressAttribute 不安全 !!!

他们声称 .NET 是安全可靠的!但是如果不看源码,就会被误导而出错!

下面的代码,你是认真的吗???

https://source.dot.net/#System.ComponentModel.Annotations/System/ComponentModel/DataAnnotations/EmailAddressAttribute.cs,c3ae85dfd8a9f58c

public override bool IsValid(object? value)
{
    if (value == null)
    {
        return true;
    }

    if (!(value is string valueAsString))
    {
        return false;
    }

    // only return true if there is only 1 '@' character
    // and it is neither the first nor the last character
    int index = valueAsString.IndexOf('@');

    return index > 0 &&
           index != valueAsString.Length - 1 &&
           index == valueAsString.LastIndexOf('@');
}

看看微软的人是如何回应的。他们就不管安全问题,还说自己设计了这样一个圈套让我们踩!

https://github.com/dotnet/runtime/issues/65968