问题
我正在使用流利的验证进行模型验证,我希望它由 ValidationFilter 在 azure 函数中完成。我已经在 asp.net 核心应用程序中做到了,但我不知道如何在 azure 函数中做到这一点
代码
我的验证器
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");
}
}
}
验证模型操作过滤器
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.cs 类中
services.AddMvc(opt => opt.Filters.Add(typeof(ValidateModelAttribute)))
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<PortfolioFileModelValidator>())
我在 azure 函数中尝试过,但其中有不同的类和接口。