简体   繁体   English

异步操作过滤器不起作用。 ASP.NET Core Web API

[英]Async Action Filter not working. ASP.NET Core Web Api

I have created custom 'ValidationFilter' in order to validate request before it reaches controller, there it is:我创建了自定义“ValidationFilter”,以便在请求到达控制器之前对其进行验证,它是:

ValidationFilter class验证过滤器

using Contracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Middleware.Filters
{
    public class ValidationFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
#pragma warning disable CS8602 // Dereference of a possibly null reference.
                var errorsInModelState = context.ModelState
                    .Where(o => o.Value.Errors.Count > 0)
                    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(o => o.ErrorMessage)).ToArray();
#pragma warning restore CS8602 // Dereference of a possibly null reference.

                var errorResponse = new ErrorResponse();

                foreach(var error in errorsInModelState)
                {
                    foreach(var subError in error.Value)
                    {
                        var errorModel = new ErrorModel
                        {
                            FieldName = error.Key,
                            Message = subError
                        };

                        errorResponse.Errors.Add(errorModel);
                    }
                }

                context.Result = new BadRequestObjectResult(errorResponse);
                return;
            }

            await next();
        }
    }
}

There is simple Validator for request:请求有简单的验证器

using Contracts;
using FluentValidation;

namespace Middleware.Validators
{
    public class AddressingDtoValidator : AbstractValidator<AddressingDto>
    {
        public AddressingDtoValidator()
        {
            RuleFor(x => x.District)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.Mr)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.Quarter)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.Street)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.Building)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.Corpus)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.Building)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
            RuleFor(x => x.InstitutionName)
                .NotNull()
                .NotEmpty()
                .Matches("^[a-zA-Z0-9 ]*$");
        }
    }
}

I have also "ErrorModel" and "ErrorResponse" classes which you can see below and my goal is to display error using this class but somemwhy it doesn't work:我也有“ErrorModel”和“ErrorResponse”类,你可以在下面看到,我的目标是使用这个类显示错误,但是为什么它不起作用:

ErrorModel错误模型

namespace Contracts.ViewModels
{
    public class ErrorModel
    {
        public string? FieldName { get; set; }
        public string? Message { get; set; }
    }
}

ErrorResponse class错误响应

namespace Contracts.ViewModels
{
    public class ErrorResponse
    {
        public List<ErrorModel> Errors { get; set; } = new List<ErrorModel>();
    }
}

I want the error to be displayed like this:我希望错误显示如下:

{
   "errors": [
     {
        "fieldname": "....",
        "message": "...."
     }
   ]
}

but instead, i get something like that:但相反,我得到了类似的东西:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-b9157268dc1f793004182694c1acf1a7-67fd063ebec5cbc3-00",
  "errors": {
    "Quarter": [
      "'Quarter' must not be empty."
    ]
  }
}

I mean this type of error is understandable and okay to read but i am practicing with action filters and something is not working.我的意思是这种类型的错误是可以理解的并且可以阅读,但是我正在练习使用动作过滤器并且某些东西不起作用。

There is also Program.cs class where i inject this validator in pipeline:还有一个Program.cs类,我在管道中注入了这个验证器:

builder.Services.AddControllers(options =>
{
    options.Filters.Add<ValidationFilter>();
})
    .AddFluentValidation(configuration => configuration.RegisterValidatorsFromAssemblyContaining<AddressingDtoValidator>());

So what could be the problem, am i missing something?那么可能是什么问题,我错过了什么吗?

To disable the default model state handling, you need to add the below setting in Program.cs .要禁用默认模型状态处理,您需要在Program.cs中添加以下设置。

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM