Andy
Andy

Reputation: 2749

C# WebAPI 2 Deserialization Produces Nulls but No Exception

I'm using WebAPI 2 / Newtonsoft.Json 9.0.1 and have run into a deserialization problem. I have an endpoint that takes a DTO as its only parameter. When the method is called, only ONE of the DTO properties is being deserialized and the rest of the properties are nulls or default values. The issue is being caused by a nested property whose type is an interface instead of a concrete type. This is the same issue being reported here.

I know that I can fix the issue by either changing the type to a concrete type or adding a type initializer onto the existing interface property like the following:

IAddressDTO Address { get; set; } = new AddressDTO();

My question is: why is no .NET exception/error thrown during deserialization? If there's a problem with deserialization, I'd like to know at run-time instead of it just using "null" everywhere. This caused a huge problem for me in Production that could've been avoided if the exception were thrown as I would've expected.

If I create a unit test like the following, it DOES throw an exception. How/why is WebAPI swallowing this exception and how do I make it stop doing that? Do I need a custom filter or something? This seems like it should be default behavior.

Here's an NUnit test that DOES throw an exception that I would like to see when running the WebAPI endpoint.

[Test]
public void DeserializationIssue()
{
    string json = @"{
        ""OrderNumber"":155,
        ""Person"":{
            ""FirstName"":""AAAA"",
            ""LastName"":""B"",
            ""Address"":{
                ""line1"":""1234 Easy St"",
            }
        }
    }";
    PatientDTO patientDTO = JsonConvert.DeserializeObject<PatientDTO>(json);
    Assert.That(patientDTO.Person.Address.Line1, Is.EqualTo("1234 Easy St"));
}

Upvotes: 3

Views: 637

Answers (1)

Robert Patterson
Robert Patterson

Reputation: 520

RE: why is no .NET exception/error thrown during deserialization?

I bet the exception is occurring and your just not set up to detect it. See this artificial for information on the webapi and global exception handling: https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling.

If the data is questionable, and you know this Deserializing could fail, you'll probably want to wrap it in a try/catch and take appropriate action.

Upvotes: 1

Related Questions