使用 aspnet Identity 进行附加验证

Additional Validation using aspnet Identity

我正在使用 AspnetIdentity 进行额外的验证,但它不起作用给我这个错误。这是我的界面代码。

using Health.BLL.CustomModels.UserModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Health.BLL.AuthRepository
{
    public interface IAuthRepository
    {
        Task<IdentityResult> RegisterUser(UserModel userModel);
        Task<IdentityUser> FindUser(string userName, string password);
        Task<IList<string>> GetRolesAsync(string userid);
        Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class;
    }
}

错误参考请看下图

The type 'TUser' cannot be used as type parameter 'TUser' in the generic type or method 'UserManager'. There is no implicit reference conversion from 'TUser' to 'Microsoft.AspNet.Identity.IUser'.

enter image description here

穆罕默德,也许您使用的 Nuget 包有问题?...

我已尝试重现您的错误,但一切正常!我在使用 Asp.Net Core 2.2 的项目中测试了您的代码,在另一个使用 Asp.Net Core 3.0/3.1 的项目中测试了您的代码。

对于 Asp.Net Core 2.2 中的项目,我安装了 Nuget 包 Microsoft.AspNet.Identity.EntityFrameworkCore 版本 2.2.3。

对于在 Asp.Net Core 3.0/3.1 中制作的项目,我安装了相同的 Nuget 包,但版本为 3.1.3。

以及我用来测试的代码:

using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace WebApplication1
{
    public interface IAuthRepository
    {
        Task<IdentityUser> FindUser(string userName, string password);
        Task<IList<string>> GetRolesAsync(string userid);
        Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user) where TUser : class;
    }
}

也许您应该使用您在项目中使用的 Asp.Net 框架的版本以及您正在使用的 Nuget 身份包来编辑您的问题。

传给UserManager的泛型需要实现接口IUser<TKey>,其中TKey是你用户的key类型,可以是string,int等

因此,假设您的用户密钥类型 (TKey) 是字符串,将 ValidateAsync 的约定更改为:

Task<IdentityResult> ValidateAsync<TUser>(UserManager<TUser> manager, TUser user) 
    where TUser : class, IUser<string>;

详情请参考文档:https://docs.microsoft.com/en-us/previous-versions/aspnet/dn468199(v=vs.108

试一试,如果有效请告诉我。