Problem
I am using fluent validation for model validation and I want it to be done by ValidationFilter in azure function. I already did it in asp.net core app but I don't know how to do it in azure functions
Code
MyValidator
using FluentValidation;
namespace MyLocker.Models.Validations
{
public class PortfolioFolderVMValidator : AbstractValidator<PortfolioFolderVM>
{
public PortfolioFolderVMValidator()
{
RuleFor(reg => reg.Title).NotEmpty().WithName("Title").WithMessage("{PropertyName} is required");
RuleFor(reg => reg.UserId).NotEmpty().WithName("UserId").WithMessage("{PropertyName} is required");
}
}
}
Validate Model Action Filter
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc.Filters;
using MyLocker.Models.Common;
namespace MyLocker.WebAPI.Attributes
{
public sealed class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errors = context.ModelState.Keys.SelectMany(key => context.ModelState[key].Errors.Select(error => new ValidationError(key, error.ErrorMessage))).ToList();
context.Result = new ContentActionResult<IList<ValidationError>>(HttpStatusCode.BadRequest, errors, "BAD REQUEST", null);
}
}
}
}
Startup
after that add it in startup.cs class like this
services.AddMvc(opt => opt.Filters.Add(typeof(ValidateModelAttribute)))
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<PortfolioFileModelValidator>())
I tried it in azure function but there are different classes and interface in it.
At present , there are 2 types of filter are available with Azure function:
FunctionInvocationFilterAttribute
As the name indicates, Filter used to execute PRE and POST processing logic when target job function is invoked.
FunctionExceptionFilterAttribute
Exception Filter will be called whenever there is an exception thrown by the Azure Function.
But you can write a wrapper on top of Azure function which will help you write the clean code.
For the wrapper based implementation , you can refer below code repo:
https://gist.github.com/bruceharrison1984/e5a6aa726ce726b15958f29267bd9385#file-fluentvalidation-validator-cs
Also alternatively you can implement the pipeline for validation the data model passed to azure function. You can find the complete reference in below repo:
https://github.com/kevbite/AzureFunctions.GreenPipes/tree/master/src/AzureFunctions.GreenPipes
Out of these 2 approach, Wrappers is more cleaner and easier to implement.
Let me know if you need any other help.