我试图获取验证器类实例,而不是在我的方法中手动启动。
我正在使用 Asp .net core webapi 2,我在启动类中注册我的验证器
services.AddMvc().AddFluentValidation().
Run Code Online (Sandbox Code Playgroud)
在我的一种操作方法中,我必须验证规则集。所以我在本地创建我的验证器类
var validator = new MyClassValidator()
var result = validator.Validate(obj,ruleSet: "RulesetName");
Run Code Online (Sandbox Code Playgroud)
我试图避免这种说法var validator = new MyClassValidator()。我想使用 IOC 并获取一个实例。有什么帮助吗?
我正在尝试编写一个自定义验证器,它将使用 OrmLite 检查数据库中是否存在实体。问题是 IRuleBuilder 的类型参数无法再从使用中推断出来。
我必须像这样编写方法调用:
RuleFor(r => r.Id).Exists<DtoName, int, EntityName>()
Run Code Online (Sandbox Code Playgroud)
但我想这样写:
Rulefor(r => r.Id).Exists<EntityName>()
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为 IRuleBuilder 有两个类型参数,并且该方法是扩展方法。是否有一种聪明、流畅的方法来设计这个并使函数调用最好像第二个版本一样?
这是我的扩展方法和验证器的代码:
public static class AbstractValidatorExtensions
{
public static IRuleBuilderOptions<T, TProperty> Exists<T, TProperty, U>(this IRuleBuilder<T, TProperty> ruleBuilder)
{
return ruleBuilder.SetValidator(new EntityExistsValidator<U>());
}
}
public class EntityExistsValidator<T> : PropertyValidator
{
public EntityExistsValidator() : base("Entity does not exist") {}
protected override bool IsValid(PropertyValidatorContext context)
{
return HostContext.Resolve<Repository>()
.Exists<T>((int)context.PropertyValue);
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的三层ASP.NET Core WebAPI应用程序:
Entities、Data interfaces和对象(这是唯一的输入和输出对象)Services。DTO因此,“域的接口”是接受输入 DTO 并返回输出 DTO 的服务。Data interfaces(数据存储库)和 CodeFirst 迁移的实施。WebAPI 项目在控制器中返回“输出”DTO。对于接受负载的端点,使用“输入”DTO。控制器与域中的服务非常相似。控制器向世界公开域服务(显然是域的接口)。
但接下来是验证......我熟悉 FluentValidation 和 ASP.NET Core 管道 - 它是一个很棒的中间件:
services.AddControllers()
.AddFluentValidation(opt =>
{
opt.RegisterValidatorsFromAssemblyContaining(typeof(PersonInputValidator));
});
Run Code Online (Sandbox Code Playgroud)
我对每个“输入”DTO 实施验证,这效果很好,但是......我不确定这是否足够。如果您参加任何服务课程,它几乎都没有经过验证。它是 .NET Core 中间件,从技术上验证控制器的输入。
我应该再次在服务中“双重验证”吗?如果是这样,是否有一种顺利的方法来重用我已有的验证器?
c# validation fluentvalidation .net-core asp.net-core-webapi
我有这个验证器:
public class InputValidator : AbstractValidator<InputData>
{
public InputValidator()
{
RuleFor(inputData => inputData.Ucl).GreaterThan(0).....;
RuleForEach(inputData => inputData.Loads).ChildRules(inputData => {
inputData.RuleFor(load => load.Position).GreaterThan(0).....);
});
... etc
Run Code Online (Sandbox Code Playgroud)
但是:位置(在每个负载中)也必须小于 Ucl(在输入数据中)。如何为这种关系(父参数与子参数)制定规则?
我正在使用 FluentValidation 设计用户注册屏幕。
我想建立一个控制机制,提供有关所有步骤的信息,如下所示。
我尝试过的代码;
RuleFor(p => p.Password).Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.");
RuleFor(p => p.Password).Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.");
RuleFor(p => p.Password).Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.");
RuleFor(x => x.Password).Matches(@"[\!\?\*\.]*$").WithMessage("Your password must contain at least one (!? *.).");
Run Code Online (Sandbox Code Playgroud)
但我无法达到我想要的结果。我还查看了 FluentValidation 文档,但没有看到任何有用的示例。
如果您有帮助,我会很高兴。
谢谢。
regex fluentvalidation asp.net-mvc-4 asp.net-core asp.net-core-3.1
这是迄今为止我的 C# 应用程序中对密码的流畅验证
\nRuleFor(request => request.Password)\n .NotEmpty()\n .MinimumLength(8)\n .Matches("[A-Z]+").WithMessage("'{PropertyName}' must contain one or more capital letters.")\n .Matches("[a-z]+").WithMessage("'{PropertyName}' must contain one or more lowercase letters.")\n .Matches(@"(\\d)+").WithMessage("'{PropertyName}' must contain one or more digits.")\n .Matches(@"[""!@$%^&*(){}:;<>,.?/+\\-_=|'[\\]~\\\\]").WithMessage("'{ PropertyName}' must contain one or more special characters.")\n .Matches("(?!.*[\xc2\xa3# \xe2\x80\x9c\xe2\x80\x9d])").WithMessage("'{PropertyName}' must not contain the following characters \xc2\xa3 # \xe2\x80\x9c\xe2\x80\x9d or spaces.")\n .Must(pass => !blacklistedWords.Any(word => pass.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0))\n .WithMessage("'{PropertyName}' contains a word that is not allowed.");\nRun Code Online (Sandbox Code Playgroud)\n以下部分目前不起作用
\n.Matches("(?!.*[\xc2\xa3# \xe2\x80\x9c\xe2\x80\x9d])").WithMessage("'{PropertyName}' must not contain the following …Run Code Online (Sandbox Code Playgroud) 我刚刚开始熟悉ServiceStack并且已经开始使用FluentValidation了.我已经按照介绍并创建了一个小型Hello应用程序.
我的问题是,当我尝试验证请求DTO时,没有返回错误消息来描述验证失败的方法,只有空白的Json对象{}.
我自己,我认为验证是自动连接到DTO所以我不需要编写任何额外的代码.
答案可能是公然但我看不到它.任何帮助将不胜感激.我的代码如下:
namespace SampleHello2
{
[Route("/hello")]
[Route("/hello/{Name}")]
public class Hello
{
public string Name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
public class HelloService : Service
{
public object Any(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
public class HelloValidator : AbstractValidator<Hello>
{
public HelloValidator()
{
//Validation rules for all requests
RuleFor(r => r.Name).NotNull().NotEmpty().Equal("Ian").WithErrorCode("ShouldNotBeEmpty"); …Run Code Online (Sandbox Code Playgroud) 我们有一些请求过滤器,也使用验证功能.
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class MyFilterAttribute : Attribute, IHasRequestFilter
{
...
}
Run Code Online (Sandbox Code Playgroud)
在AppHost中:
public override void Configure(Container container)
{
....
Plugins.Add(new ValidationFeature());
....
}
Run Code Online (Sandbox Code Playgroud)
我需要在请求过滤器之后运行流畅的验证,因为一些过滤器会将数据添加到dto然后进行验证.我已经看到了操作顺序但是没有说明验证的位置......至少我没有看到.
任何帮助,将不胜感激.
好吧我的问题是来自fluentValidation的modelvalidator在我的项目中不起作用,并且无论验证状态如何,ModelState.IsValid始终为true,我提前使用asp.net mvc 4,.net 4.5,thx.
Global.asax中
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
FluentValidationModelValidatorProvider.Configure();
}
Run Code Online (Sandbox Code Playgroud)
LoginViewModel
using FluentValidation.Attributes;
namespace ViewModel.Cuentas
{
[Validator(typeof(LoginViewModel))]
public class LoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
LoginViewModelValidator
using FluentValidation;
using FluentValidation.Results;
namespace ViewModel.Cuentas.Validadores
{
public class LoginViewModelValidator : AbstractValidator<LoginViewModel>
{
public LoginViewModelValidator()
{
RuleFor(x => x.UserName).NotEmpty().WithMessage("El Campo Usuario es Necesario");
RuleFor(x => x.Password).NotEmpty().WithMessage("El Campo Usuario es Necesario");
}
}
}
Run Code Online (Sandbox Code Playgroud)
和我的帐户管理员
Run Code Online (Sandbox Code Playgroud)[HttpPost] …
fluentvalidation ×10
c# ×7
servicestack ×3
validation ×3
asp.net-core ×2
regex ×2
.net-core ×1
asp.net-mvc ×1