我想在创建新帐户之前验证数据库中是否存在很少的自定义字段 . 为了证明我的问题,我将使用电子邮件 . 这是我的代码:

public override Task<IdentityResult> CreateAsync(User user, string password)
{
    if (Users.Any(u => u.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)))
    {
        var identityResult = new IdentityResult(new []{"Email exists"});
        return identityResult;
    }
    return base.CreateAsync(user, password);
}

所以概念很简单,如果电子邮件已经存在,则不允许用户创建帐户 . 我试图将我的验证逻辑从控制器转移到服务中 . 所以控制器像这样调用它:

var result = await _userService.CreateAsync(user, model.Password);

然后根据结果做不同的事情 .

上面的代码不起作用,我该如何返回错误?

Cannot convert expression type 'IdentityResult' to return type Task<IdentityResult>

编辑:我需要向我的CreateAsync方法添加异步字并等待基数,所以它应该是:

public override async Task<IdentityResult> CreateAsync(User user, string password)
{
    if (Users.Any(u => u.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)))
    {
        var identityResult = new IdentityResult(new []{"Email exists"});
        return identityResult;
    }
    return await base.CreateAsync(user, password);
}