Search code examples
.net-coreazure-functionsmodelstate

How to validate parameters sent to an Azure function?


I m new to Azure Function. I m used to code with WebApi where I have an ActionExecutingContext which helps to validate the ModelState. I created an ActionFilterAttribute which do it automatically:

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class ValidateModelStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            //Do something
        }
    }
}

How can I do that or something similar with Azure function?

For example with this DTO with a name property set as Required:

public class TestDto
{
    [Required]
    public string Name { get; set; }
}

Solution

  • I created an easy extension which validate the object and set an out parameter with the collection of errors.

    public static class ObjectExtensions
    {
        public static bool IsValid(this object o, out ICollection<ValidationResult> validationResults)
        {
            validationResults = new List<ValidationResult>();
            return Validator.TryValidateObject(o, new ValidationContext(o, null, null), validationResults, true);
        }
    }
    

    So in my Azure function, here is what I have:

        [FunctionName("Create")]
        public async Task<IActionResult> CreateAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "test/")] TestDto dto,
            CancellationToken cts,
            ILogger log)
        {
            if (!dto.IsValid(validationResults: out var validationResults))
            {
                return new BadRequestObjectResult($"{nameof(TestDto)} is invalid: {string.Join(", ", validationResults.Select(s => s.ErrorMessage))}");
            }
            var result = await _testManager.CreateAsync(new Test() { Name = dto.Name }, cts);
            return new OkObjectResult(result);
        }