2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've done it in a similar way once (gist.github.com/MilkyWayJoe/4422478) but resumed to use the WebAPIAdapter & Serializer. They need some work, but make it a lot easier as I don't have to change backend API in any way.
Yes, it depends which side you want (or even can) bend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.