Reputation: 2860
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
Upvotes: 0
Views: 1344
Reputation: 12715
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; }
}
Upvotes: 1
Reputation: 4668
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.
Upvotes: 0