McArthey McArthey - 8 months ago 37
JSON Question

Change Web Api 2 Post method to accept modified body

Currently I have an API that is receiving an object type as below.

public HttpResponseMessage Post(Job job) {}

When receiving a straight (or partial) object which matches the
type everything works as expected. The issue is that we are modifying the JSON object to include more information in the body which is preventing the serializer from knowing how to handle this.
Our new request is as follows.


The "old" object we had received is now in the "payload". Do I need to override a method, perhaps a Media Formatter?



Create a type that contains your Job type as a property named Payload with another property named HttpHeaders that contains the expected model structure. I don't know why you're sending Http headers in the payload body.

The model binding will attempt to match the structure of the request body to the structure of the expected model. In this case, you're going from expecting type Job, to accepting a type that contains Job. So, you would create a super type like this:

public class InputModel {
    public Job Payload {get;set;}
    public HeaderType HttpHeaders {get;set;}

The ASP.NET model binding will then populate the objects accordingly.