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

1

2 Answers 2

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

I tried this Giddy, but don't know why the control isn't hitting this piece of code, appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.