javisrk javisrk - 1 year ago 84
C# Question

Passing a object with a list to Web API

I'm having trouble passing a list of objects via JSON to Web Api.

The method:

public HttpResponseMessage SubmitCourierRequest([FromBody]CRRequest request)
//code goes here

The CRRequest object:

public class CRRequest
public List<MediaItem> MediaItems = new List<MediaItem>();
public DistributionList DistributionList { get; set; }
public string SendTo { get; set; }
public string Subject { get; set; }
public string Comments { get; set; }

The media item class:

public abstract class MediaItem : INotifyPropertyChanged
public virtual string ID { get; set; }

public double Longitude { get; set; }

public double Latitude { get; set; }

public int AgencyID { get; set; }


The json I'm passing:

"SendTo": "bob@bob.com",
"Subject": "asda",
"Comments": "asdasd",
"ExpirationDate": "2016-11-01",
"DistributionList": {
"DistributionListID": "4"
"MediaItems": [{
"ID": "001"
"ID": "002"

When I debug the method, I can get everything but the the media items, which gives me a count of 0. Am I missing something here?

Answer Source

Its because MediaItem is marked as abstract so it cannot be instantiated as the underlying concrete type is unknown at call time.

Do you have a concrete type you can use instead (easiest/fastest solution)? Otherwise you will have to provide a binder that can identify the correct the type based on the raw json (or something else). If you are using json.net see Deserializing JSON to abstract class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download