0

I want to give a custom response when Model binding to the API fails by datatype mismatch.

Example: When someone tries to bind a string to GUID parameter in my API, currently I get following response.

    {
      "documentCategoryId": [
        "Error converting value \"string\" to type 'System.Guid'. Path 'documentCategoryId', line 2, position 32."
      ]
    }

Instead, I would like to say,

processing error

Dvyn Resh
  • 980
  • 1
  • 6
  • 14
Praveen Rao Chavan.G
  • 2,772
  • 3
  • 22
  • 33
  • Take a look at https://stackoverflow.com/questions/51145243/how-do-i-customize-asp-net-core-model-binding-errors – misticos Jul 30 '19 at 10:36

2 Answers2

1

Try to customize BadRequest response with FormatOutput method like below :

 services.AddMvc()
         .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    return new BadRequestObjectResult(FormatOutput(actionContext.ModelState));
                };
            });

Customize the FormatOutput method to your whims.

public List<Base> FormatOutput(ModelStateDictionary input)
    {
        List<Base> baseResult = new List<Base>();
        foreach (var modelStateKey in input.Keys)
        {
            var modelStateVal = input[modelStateKey];
            foreach (ModelError error in modelStateVal.Errors)
            {
                Base basedata = new Base();
                basedata.Status = StatusCodes.Status400BadRequest;
                basedata.Field = modelStateKey; 
                basedata.Message =error.ErrorMessage; // set the message you want 
                baseResult.Add(basedata);
            }
        }
        return baseResult;
    }

 public class Base
{
    public int Status { get; set; }
    public string Field { get; set; }
    public string Message { get; set; }
}
Xueli Chen
  • 11,987
  • 3
  • 25
  • 36
0

In reference to this post, to add a custom response based on your usecase add the below code In Startup

services.Configure<ApiBehaviorOptions>(o =>
{
    o.InvalidModelStateResponseFactory = actionContext =>
        new ResponseObject("403", "processing error");
});

Where ResponseObject is a custom class

 class ResponseObject{
   public string Status;
   public string Message;
   ResponseObject(string Status, string Message){
     this.Status = Status;
     this.Message= Message;
   }
 }

When model binding fails api would return response like this

{ Status : "403", Message : "processing error" }

You can customize the Response Object as you please.

Giddy Naya
  • 4,237
  • 2
  • 17
  • 30