Here is my problem, I'm developing a REST api in Asp.Net core which is used by some developers. Solution is setup to auto-generate swagger documentation, which make api testing pretty quick easy. Some of the POST methods are receving huge json objects via request body and as soon as only one of the properties generates a serialization error (ex. putting string in an integer field), the model received in my controller is null. Developers then lose some time to find out which field is making the serialization fail. I would like to be able to not only catch those errors, but return an explicit message to the developers to point out the field causing the error. I'm able to catch the error by doing this in Startup.cs file
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.Error = (sender, args) =>
{
};
});
at this point I have the serialization error detail. I could log error, but I would like to return a 400 with explicit message. I tried some messy stuff like the following to acccess the http response but couldn't achieve it.
var provider = services.BuildServiceProvider();
var http = (IHttpContextAccessor)provider.GetService(typeof(IHttpContextAccessor));
var response = http.HttpContext.Response;
ModelStateof the controller. If you're able to use 2.1's[ApiController]attribute, you'll get this mostly for free. Otherwise, you can write a customActionFilterto do it for you.