我使用最新的FluentValidation.AspNetCore(8.0.0)和Asp.net core(2.1.0)。我像下面那样实现了IActionFilter
。
public class MyActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
var a = context.ModelState.IsValid;
}
public void OnActionExecuting(ActionExecutingContext context)
{
var a = context.ModelState.IsValid;
}
}
和下面定义的我的请求模型。
public class Class1
{
public int Id { get; set; }
}
public class Class1Validator : AbstractValidator<Class1>
{
public Class1Validator()
{
RuleFor(w => w.Id).GreaterThan(2);
}
}
下面是我在控制器中的动作。
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get(Class1 c1)
{
return new string[] { "value1", "value2" };
}
[HttpPost, Route("post1")]
public IActionResult Post([FromBody]Class1 c1)
{
return Ok(c1);
}
}
以下是我在启动中的ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(opt =>
{
opt.Filters.Add<MyActionFilter>();
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddFluentValidation(cfg =>
{
cfg.RegisterValidatorsFromAssemblyContaining<Class1Validator>();
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
当我发布/api/values/post1
时,它直接返回{"Id": ["'Id' must be greater than '2'." ]}
而没有进入OnActionExecuting
上的MyActionFilter
,我该如何使其进入“ MyActionFilter”自定义代码。