简体   繁体   English

具有ASP.NET身份的模型中的独特属性

[英]Unique properties from model with ASP.NET Identity

I'm developing a WEB API asp.net project with visual studio 2013, and I'm implementing my custom Identity model for custom registration. 我正在使用Visual Studio 2013开发一个WEB API asp.net项目,并且正在实现用于自定义注册的自定义身份模型。 For example I've added an email field in the RegisterBindingModel. 例如,我在RegisterBindingModel中添加了一个电子邮件字段。

This is what I've done: How to extend asp.net web api 2 user? 这就是我所做的: 如何扩展asp.net Web API 2用户?

I've added email property, and I need that property to be unique (as UserName) , but by default that email property can be repeated. 我已经添加了email属性,并且我需要该属性是唯一的(作为UserName),但是默认情况下,电子邮件属性可以重复。 My question is how do I make this email property unique, like UserName? 我的问题是如何使该电子邮件属性(如用户名)唯一? I've read that unique properties can be set with UserValidator, but can't find how. 我读过可以使用UserValidator设置唯一属性,但找不到方法。 Can you tell me how I can make that, with UserValidator or the best way? 您能告诉我如何使用UserValidator或最佳方法吗?

And how's the UserName property defined as unique? 以及如何将UserName属性定义为唯一? I can't find it anywhere. 我在任何地方都找不到。

Thank you. 谢谢。

There a different ways to implement this, but not out of the box. 有不同的方法可以实现此目的,但并非开箱即用。 However, you can implement an extensible validation using Fluent Validation 但是,您可以使用Fluent Validation实施可扩展的验证

[Validator(typeof(ApplicationUserValidator))]
class ApplicationUser : IdentityUser
{
    public string Email { get; set; }
    //...Model implementation omitted
}

public class ApplicationUserValidator : AbstractValidator<ApplicationUser>
{
    public ApplicationUserValidator()
    {

        RuleFor(x => x.Email).Must(IsUniqueEmail).WithMessage("Email already exists");
    }
    private bool IsUniqueEmail(string mail)
    {
        var _db = new DataContext();
        if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;
        return false;
    }
    //implementing additional validation for other properties:
    private bool IsUniqueTelephoneNumber(string number)
    {
      //...implement here
    }
}

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

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