Myslik
Myslik

Reputation: 1158

Customize binding in ASP.NET Web Api

I am stuck with following problem in ASP.NET Web Api. Let say I have following code in my ApiController:

public void Post(Person person)
{
    // Handle the argument
}

What I would like to do is to accept following JSON request:

{
    "person": {
        "name": "John Doe",
        "age": 27
    }
}

I would like to go around creating some holding object for each model just to properly bind incoming data. In previous version of MVC, it was possible to define something like Prefix to solve this.

Upvotes: 2

Views: 165

Answers (1)

Myslik
Myslik

Reputation: 1158

Let me report that I have been able to solve this implementing CustomJsonMediaTypeFormatter:

public class EmberJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(
        Type type,
        System.IO.Stream readStream,
        System.Net.Http.HttpContent content,
        IFormatterLogger formatterLogger)
    {
        return base.ReadFromStreamAsync(
            typeof(JObject),
            readStream,
            content,
            formatterLogger).ContinueWith<object>((task) =>
        {
            var data = task.Result as JObject;
            var prefix= type.Name.ToLower();

            if (data[prefix] == null)
            {
                return GetDefaultValueForType(type);
            }

            var serializer = JsonSerializer.Create(SerializerSettings);

            return data[prefix].ToObject(type, serializer);
        });
    }
}

and replacing default JsonMediaTypeFormatter in GlobalConfiguration.

Upvotes: 2

Related Questions