简体   繁体   English

如何在 ASP.NET Core 3.0 中使用 ValidationAttribute 验证多个操作参数

[英]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.

相关问题 ASP.NET 核心 MVC 过滤:如何将多个值发送给操作? - ASP.NET Core MVC filtering: How can I send multiple value to action? 如何在 ASP.NET 中干净地共享数据 model、ViewModel 和 DTO 的自定义验证器 (ValidationAttribute) - How can I cleanly share a Custom Validator (ValidationAttribute) for a data model, a ViewModel, and a DTO in ASP.NET 我可以在 ASP.Net Core 3.0 中使用 IEmailSender 接口向多个接收者发送电子邮件吗 - Can I Send Emails to Multiple Receivers using IEmailSender Interface in ASP.Net Core 3.0 如何使用ASP.NET Core Identity v Preview 3.0创建自定义用户和角色? - How i can create custom user and role with ASP.NET Core identity v preview 3.0? Url.Action() 在 ASP.NET 核心 3.0 中返回 null - Url.Action() returns null in ASP.NET Core 3.0 如何验证 asp.net 核心 3.0 web api 的获取请求中的参数? - How to Validate parameter in asp.net core 3.0 web api's get request? ASP.Net Core 3.0 应用程序 URL 未找到路径参数 - ASP.Net Core 3.0 app URL was not found with Path parameters 如何手动验证 JWT Asp.Net Core? - How Do I Manually Validate a JWT Asp.Net Core? 如何验证 ASP.NET Core 中的 DI 容器? - How do I validate the DI container in ASP.NET Core? 为什么添加请求参数时我的 Request.BodyReader 为空(ASP.NET Core 3.0) - Why my Request.BodyReader is empty when i add request parameters (ASP.NET Core 3.0)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM