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

前端 未结 2 1246
北荒
北荒 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 00:57

    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. As such, your conditional testing ModelState.IsValid is essentially always false (and therefore not entered) because the only requests that will ever get this far are valid ones.

    You could simply remove the ApiController attribute, but that removes a bunch of other beneficial stuff the attributes adds as well. The better option is to use a custom response factory:

    services.Configure<ApiBehaviorOptions>(o =>
    {
        o.InvalidModelStateResponseFactory = actionContext =>
            new BadRequestObjectResult(actionContext.ModelState);
    });
    

    That's essentially what's happening by default, so you'd simply need to change the action provided there accordingly to customize it to your whims.

    0 讨论(0)
  • 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));
        }
    
    0 讨论(0)
提交回复
热议问题