我正在尝试创建自定义验证器。 我无法从自定义上下文中获取服务提供商。我正在尝试使用我的服务,但我无法做到这一点。
Fluent验证已添加到我的应用程序中,就像他们的网站建议一样。
错误消息:
'未将服务提供商配置为与 FluentValidation。利用InjectValidator或GetServiceProvider 仅在使用自动MVC集成时受支持。'
public static class ValidatorExtensions
{
public static IRuleBuilderInitial<T, string> MustBeRefreshToken<T>(this IRuleBuilder<T, string> ruleBuilder)
{
return ruleBuilder.Custom((token, contextPropertyValidatorContext) =>
{
var context = contextPropertyValidatorContext.GetServiceProvider();
var jwtSettings = (JWTSettings)context.GetService(typeof(JWTSettings));
var meblexDbContext = (MeblexDbContext)context.GetService(typeof(MeblexDbContext));
var tokenValidationParameters = jwtSettings.GetTokenValidationParameters(jwtSettings.RefreshTokenSecret);
var jwtService = (IJWTService)context.GetService(typeof(IJWTService));
try
{
var userId = jwtService.GetRefreshTokenUserId(token);
var userExist = meblexDbContext.Users.FirstOrDefault(x => x.UserId == userId);
if (userExist == null) contextPropertyValidatorContext.AddFailure("{Property Name} not connected with user");
var expTicks = int.Parse(jwtService.GetClaimValue("exp", tokenValidationParameters, token));
var expDate = DateTimeOffset.UnixEpoch.AddSeconds(expTicks);
if (! (expDate > DateTime.UtcNow))
{
contextPropertyValidatorContext.AddFailure("{Property Name} is expired");
}
}
catch
{
contextPropertyValidatorContext.AddFailure("{Property Name} is not valid");
}
});
}
}
}