3

问题

我正在使用流利的验证进行模型验证,我希望它由 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 函数中尝试过,但其中有不同的类和接口。

4

1 回答 1

2

目前,Azure 功能有两种类型的过滤器可用:

  • 函数调用过滤器属性

    顾名思义,Filter 用于在调用目标作业函数时执行 PRE 和 POST 处理逻辑。

  • FunctionExceptionFilterAttribute

    只要 Azure 函数引发异常,就会调用异常筛选器。

但是您可以在 Azure 函数之上编写一个包装器,这将帮助您编写干净的代码。

对于基于包装器的实现,您可以参考以下代码仓库:

https://gist.github.com/bruceharrison1984/e5a6aa726ce726b15958f29267bd9385#file-fluentvalidation-validator-cs

或者,您可以实现管道以验证传递给 azure 函数的数据模型。你可以在下面的 repo 中找到完整的参考:

https://github.com/kevbite/AzureFunctions.GreenPipes/tree/master/src/AzureFunctions.GreenPipes

在这两种方法中,Wrappers 更干净,更容易实现。

如果您需要任何其他帮助,请告诉我。

于 2019-09-18T09:32:45.100 回答