Core中缺少必需属性的响应

Core中缺少必需属性的响应

本文介绍了对ASP.NET Core中缺少必需属性的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下控制器:

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // POST api/values
        [HttpPost]
        public ActionResult<string> Post([FromBody] Model req)
        {
            return $"Your name is {req.Name}";
        }
    }

    public class Model
    {
        [Required] public string Name { get; set; }
    }
}

如果我发布一个空的正文 {} ,则响应为:

if I post an empty body {}, the response is:

{
    "errors": {
        "Name": [
            "The Name field is required."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "80000002-0002-ff00-b63f-84710c7967bb"
}

我想更改此响应,因此将错误消息自动传递给用户变得更加容易.所以我希望它看起来像这样:

I would like to change this response, so it becomes easier to automatically pass the error message on to the user. So I would like it to look more like this:

{
    "error": 999,
    "message": "Field 'name' is required."
}

我试图像这样扩展 RequiredAttribute 类:

public class MyRequiredAttribute : RequiredAttribute
{
    public MyRequiredAttribute()
    {
        ErrorMessage = "{0} is required";
    }
}

可悲的是,它只能更改集合中返回的字符串,就像这样

which sadly only changes the returned string in the collection, like so

{
    "errors": {
        "Name": [
            "Name is required"
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "80000006-0000-ff00-b63f-84710c7967bb"
}

推荐答案

在使用应用了ApiController属性的控制器时,ASP.NET Core通过返回带有ModelState作为响应主体的400 Bad Request来自动处理模型验证错误.它与自动HTTP 400响应.您可以自定义BadRequest响应,如下所示:

When utilizing a controller with the ApiController attribute applied, ASP.NET Core automatically handles model validation errors by returning a 400 Bad Request with ModelState as the response body. It is related to Automatic HTTP 400 responses . You could customize BadRequest response like below :

  services.AddMvc()
                .ConfigureApiBehaviorOptions(options =>
                {
                    options.InvalidModelStateResponseFactory = actionContext =>
                    {
                        var modelState = actionContext.ModelState;
                        return new BadRequestObjectResult(FormatOutput(modelState));
                    };
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

根据自己的想法自定义 FormatOutput 方法.

Customize the FormatOutput method to your whims.

public List<Base> FormatOutput(ModelStateDictionary input)
    {
        List<Base> baseResult = new List<Base>();
        foreach (var modelState in input.Values)
        {
            foreach (ModelError error in modelState.Errors)
            {
                Base basedata = new Base();
                basedata.Error = StatusCodes.Status400BadRequest;
                basedata.Message =error.ErrorMessage;
                baseResult.Add(basedata);
            }
        }
        return baseResult;
    }

public class Base
{
    public int Error { get; set; }
    public string Message { get; set; }
}

这篇关于对ASP.NET Core中缺少必需属性的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 12:11