4

I am having a problem with silently failing deserialization in ASP.NET Web API (version 5.1.2). I would like the deserialization to raise an error instead but I am unable to find a configuration for it.

My specific (simplified) case is this. A client application (AngularJS) sends a HTTP POST request to the ASP.NET Web API backend. As a payload there are a bunch of strings:

["ABC100", "ABC200", "ABC300"]

However, the server is expecting a list of integers:

List<int> Ids { get; set; }

What ends up happening is that the deserialization fails, the Ids list will be empty and there are no errors.

Ids: []

Of course the mismatch needs to be fixed as well, but it seems obvious to me that the POST request should fail in this case. How can I make it the default?

4
  • JavaScript will always return an array, it doesn't understand List<T>. List is a C# thing. And you are expecting int, whereas the values send by client are not. Commented Nov 23, 2015 at 9:11
  • 1
    In your API method, you can do any kinds of checks you want on the data (although this is happening after the deserialization) and manually return an HTTP 500: asp.net/web-api/overview/error-handling/exception-handling Commented Nov 23, 2015 at 9:15
  • @modal_dialog of course I can make checks against the Ids list, but it is quite valid that it is empty. Just not in the case when the client sends data but the types do not match. Commented Nov 23, 2015 at 9:24
  • as a work around, create a custom media type formatter, handle the serialization/deserialization manually. Commented Nov 23, 2015 at 10:03

1 Answer 1

1

One solution to this problem seems to be checking the ModelState.IsValid property right at the start of the controller method:

[HttpPost]
[Route("Stuff/Ids/")]
public void PostStuff(List<int> Ids)
{
    if(!ModelState.IsValid)
        throw new Exception("ModelState is not valid.");

    // Carry on...
}

The ModelState.IsValid is indeed false in the case described by my question.

The check can be made global by creating an action filter out of it. Instructions for this can be found for example in this article: Model Validation in ASP.NET Web API

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

Comments

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.