A Bugfix - .NET Core Api not binding DTO props to json payload

March 14, 2021

Not long ago I was hacking on a side project where a JSON payload, sent to an API, was somehow not binding to the C# DTO object on the backend. Firefox was showing the request with the payload, but none of the properties were binding in the ApiController. I debugged and debugged, sent the JSON over and over. No matter what I tried the API had null set for both properties, so frustrating!

It took longer than I would like to admit, I tried all sorts of things. The request was not different than others, other APIs were just fine, but not this one.

Eventually, something jumped out.

This was the DTO definition:

public class AddAlbumMultipleRequest
    public int AlbumId { get; internal set; }
    public int[] MediaItemIds { get; internal set; }

If you look really closely, you’ll notice internal set on those properties. This stood out as my DTOs were in another assembly containing my common objects and not the assembly of the API. This means when I send requests, the properties cannot bind as the set is inaccessible from the api assembly and the runtime cannot bind the values. Oof! I must have copied a class from another and failed to remove these. 😢

The fix was to remove the internal access modifier.

public class AddAlbumMultipleRequest
    public int AlbumId { get; set; }
    public int[] MediaItemIds { get; set; }

Hope this helps someone if you’re web api DTOs are not binding to the JSON payload. It’s a silly mistake, but cost me a few hours on a hobby project.

Hi there. I'm Lee McKinnon and I live in the Greater Boston area. I build software for Investment professionals and poke around all things tech. You can follow me on Twitter