How to customize error response in web api with .net core?

前端 未结 2 1271
北荒
北荒 2021-01-13 00:53

I am using .net core 2.2 with web api. I have created one class i.e. as below :

public class NotificationRequestModel
{
    [Required]
    public string Dev         


        
2条回答
  •  春和景丽
    2021-01-13 01:00

    As Chris analized, your issue is caused by Automatic HTTP 400 responses .

    For the quick solution, you could supress this feature by

    services.AddMvc()
            .ConfigureApiBehaviorOptions(options => {
                options.SuppressModelStateInvalidFilter = true;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    

    For a efficient, you could follow suggestion from Chris, like below:

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

    And, there is no need to define the code below any more in your action.

    if (!ModelState.IsValid)
        {
            return BadRequest(FormatOutput(ModelState.Values));
        }
    

提交回复
热议问题