0

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;
4
  • 2
    You can retrieve more information about the error from the ModelState of 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 custom ActionFilter to do it for you. Commented Nov 1, 2018 at 20:03
  • @KirkLarkin: Can you check my comment on the accepted answer? I am having this weird behaviour. I was expecting it to behave as you and the Tao Zahou suggested below but it just responds back without reaching action method...! Commented May 26, 2019 at 18:05
  • @MilindThakkar Have a look at this explanation: stackoverflow.com/questions/51870603/…. Commented May 26, 2019 at 19:09
  • @KirkLarkin: I am yet to grasp .Net core fully. just started. But this makes no sense ! I mean its taking control out of developer's hand ! And make them work more if wants to control. My incoming JSON is Invalid, I know, it shouldn't be... as most compiler won't allow. But how to stop tester who is using just PostMan and thinks removing value of an Integer attribute is a test case :-( Commented May 26, 2019 at 19:24

1 Answer 1

3

For catching model error, you could try ModelState, and you could try code below to return 400 with detail error message.

        [HttpPost("PostWithInValidate")]
    public async Task<IActionResult> PostWithInValidate([FromBody]InValidateVM vM)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return Ok(vM);
    }

Note

As the suggestion from @Kirk Larin, if you could use [ApiController] attribute on controller, there is no need to use above code.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi I am having a weird issue. In my .Net Core 2.0 WebAPI, I have exactly same code as you have suggested above. However, in case when invalid JSON is sent, it doesn't even reach the action method. It simply throws back error "Unexpected character encountered while parsing value: ,. Path 'RootClass[0].IdNumber', line 6, position 20." without even reaching the action method breakpoint...My controller is having [ApiController] attribute... Any idea where to look for. Search on Google gets me similar answers to what you have said... but that's how my code is... What am I missing!?

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.