Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Json Post Values with asp.net webapi

i'm making a request do a asp.net webapi Post Method, and i'm not beeing able to get a request variable.

Request

jQuery.ajax({ url: sURL, type: 'POST', data: {var1:"mytext"}, async: false, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=UTF-8' })
    .done(function (data) {
        ...
    });

WEB API Fnx

    [AcceptVerbs("POST")]
    [ActionName("myActionName")]
    public void DoSomeStuff([FromBody]dynamic value)
    {
        //first way
        var x = value.var1;

        //Second way
        var y = Request("var1");

    }

i Cannot obtain the var1 content in both ways... (unless i create a class for that)

how should i do that?

like image 372
Flavio CF Oliveira Avatar asked Oct 29 '12 11:10

Flavio CF Oliveira


People also ask

How do I get JSON post data?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

How do I get a value from the body of a Web API post?

The item parameter is a complex type, so Web API uses a media-type formatter to read the value from the request body. To get a value from the URI, Web API looks in the route data and the URI query string. The route data is populated when the routing system parses the URI and matches it to a route.


1 Answers

First way:

    public void Post([FromBody]dynamic value)
    {
        var x = value.var1.Value; // JToken
    }

Note that value.Property actually returns a JToken instance so to get it's value you need to call value.Property.Value.

Second way:

    public async Task Post()
    {        
        dynamic obj = await Request.Content.ReadAsAsync<JObject>();
        var y = obj.var1;
    }

Both of the above work using Fiddler. If the first option isn't working for you, try setting the content type to application/json to ensure that the JsonMediaTypeFormatter is used to deserialize the content.

like image 138
Ben Foster Avatar answered Oct 11 '22 10:10

Ben Foster