How to get POST data in WebAPI?

From answer in this question:
How to get Json Post Values with asp.net webapi

  1. Autoparse using parameter binding; note that the dynamic is made up of JToken, hence the .Value accessor.

    public void Post([FromBody]dynamic value) {
        var x = value.var1.Value; // JToken
    }
    
  2. Read just like Request.RequestUri.ParseQueryString()[key]

    public async Task Post() {        
       dynamic obj = await Request.Content.ReadAsAsync<JObject>();
       var y = obj.var1;
    }
    
  3. Same as #2, just not asynchronously (?) so you can use it in a helper method

    private T GetPostParam<T>(string key) {
        var p = Request.Content.ReadAsAsync<JObject>();
        return (T)Convert.ChangeType(p.Result[key], typeof(T)); // example conversion, could be null...
    }
    

Caveat — expects media-type application/json in order to trigger JsonMediaTypeFormatter handling.

Leave a Comment