[英]How can I validate multiple action parameters with ValidationAttribute in ASP.NET Core 3.0
Consider the following controller action signatures:考虑以下控制器动作签名:
[HttpGet]
public IEnumerable<Whatever> Get(DateTime from, DateTime to)
Or或者
[HttpGet]
public Whatever Get(int amount, SomeUnit unit)
I'd like to be able to run a validation on parameters supplied by the caller.我希望能够对调用者提供的参数进行验证。 In both cases what passes as valid input in the first parameter depends on the value of second one.
在这两种情况下,第一个参数中作为有效输入传递的内容取决于第二个参数的值。
So far I have failed to find an explanation or example of how this can be achieved with validation attributes in ASP.NET Core 3.0到目前为止,我还没有找到解释或示例,说明如何使用 ASP.NET Core 3.0 中的验证属性来实现这一点
I see that for example CustomValidationAttribute allows using it on methods.我看到例如CustomValidationAttribute允许在方法上使用它。 I can give it a method that IsValid will delegate to and provide object and validation context:
我可以给它一个 IsValid 将委托给它并提供对象和验证上下文的方法:
IsValid(Object, ValidationContext)
I checked documentation of both IsValid and ValidationContext and I cannot find any hint on how would I access the parameters passed to the validated action.我检查了 IsValid 和 ValidationContext 的文档,但找不到有关如何访问传递给已验证操作的参数的任何提示。
While googling for hints I found an excerpt from " Pro ASP.NET Web API " HTTP Web Services in ASP.NET" where they implement something similar. The excerpt ends however before the code is shown and I don't have that book (didn't find a corresponding book but on ASP.NET Core).在谷歌搜索提示时,我发现了“ Pro ASP.NET Web API ”HTTP Web Services in ASP.NET 的摘录,他们在其中实现了类似的东西。但是在代码显示之前摘录结束了,我没有那本书(没有找不到相应的书,而是在 ASP.NET Core 上)。
CustomValidationAttribute
is used for properties and parameters. CustomValidationAttribute
用于属性和参数。 For an action validation you should write your own filter.对于动作验证,您应该编写自己的过滤器。 Here is an example:
下面是一个例子:
public class MyValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if(context.ModelState.IsValid)
{
var dateFrom = (DateTime)context.ActionArguments["from"];
var dateTo = (DateTime)context.ActionArguments["to"];
if(dateFrom <= dateTo)
{
// continue the flow in pipeline
return;
}
}
context.Result = new BadRequestResult();
}
}
And then you can use it in your controller:然后你可以在你的控制器中使用它:
[HttpGet]
[MyValidation]
public IEnumerable<Whatever> Get(DateTime from, DateTime to)
{
// Here ModelState.IsValid is true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.