Use custom validation responses with fluent validation

前端 未结 4 1205
天命终不由人
天命终不由人 2020-12-29 12:46

Hello I am trying to get custom validation response for my webApi using .NET Core.

Here I want to have response model like

[{
  ErrorCode:
  ErrorFi         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 13:11

    try with this:

    services.Configure(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });
    

    I validate the model with fluentvalidation, after build the BadResquest response in a ActionFilter class:

    public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0)
                        .SelectMany(v => v.Errors)
                        .Select(v => v.ErrorMessage)
                        .ToList();
    
                var responseObj = new
                {
                    Message = "Bad Request",
                    Errors = errors                    
                };
    
                context.Result = new JsonResult(responseObj)
                {
                    StatusCode = 400
                };
            }
        }
    }
    

    In StartUp.cs:

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelStateAttribute));
            })
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining());
    
            services.Configure(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
    

    And it works fine. I hope you find it useful

提交回复
热议问题