我是一名初级程序员,尝试编写一小段代码来测试FluentValidation,但没有手动调用验证程序并使用.AddToModelState将结果添加到模型状态,我无法使ModelState.IsValid识别验证中存在错误。我在某处丢失集成吗?ModelState.IsValid在使用FluentValidation时总是评估为true
这是我的价值模型,只是一个具有两个预设值的字符串数组。
using FluentValidation.Attributes;
using Playground2.Validators;
namespace Playground2.Models
{
[Validator(typeof(ValueValidator))]
public class Value
{
public string[] values = { "value1", "" };
}
}
这是我的验证器,查找5到10个字符之间的两个值。
using FluentValidation;
using Playground2.Models;
namespace Playground2.Validators
{
public class ValueValidator : AbstractValidator<Value>
{
public ValueValidator()
{
RuleFor(x => x.values[0]).Length(5, 10);
RuleFor(x => x.values[1]).Length(5, 10);
}
}
}
在ValuesController中,我只是简单地创建一个值对象并运行检查以查看它是否在输出前通过验证。
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Playground2.Models;
using System.Collections.Generic;
namespace Playground2.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
var value = new Value();
if (!ModelState.IsValid)
{
return new string[] { "Not valid" };
}
else
{
return value.values;
}
}
但在运行时,该ModelState.IsValid一直在评估为真,但送入值的信息是默认无效。
我想它只会通过模型绑定来查看(请求)参数。由于没有('Get()'),请求是有效的。 – Caramiriel