Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post JSON string to WEB API

I have an ASP.NET WEB-API 2 app witch needs to have a POST method that accepts a JOSN string with unknown structure from javascript.
I enabled cors and GET methods works fine, however when sending JSON from the client the api's method parameter is always null.
This is my api method:

//parameters i tried:
//[FromBody]string model
//[FromBody]dynamic model
//dynamic model
public HttpResponseMessage Post(string model)
{
    return new HttpResponseMessage()
    {
        Content = new StringContent("POST: Test message: " + model)
    };
}

and my client method:

function sendRequest()
{
    var Test = {"Name":"some name"};
    var method = $('#method').val();

    $.ajax({
        type: method,
        url: serviceUrl,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(Test)               
    }).done(function (data)
    {
        $('#value1').text(data);
    }).error(function (jqXHR, textStatus, errorThrown)
    {
        $('#value1').text(jqXHR.responseText || textStatus);
    });
}

So the question is how can I post an unknown JSON string from javascript and accept it as a string in my api method?

like image 587
Yoav Avatar asked Apr 12 '16 08:04

Yoav


People also ask

How do I post JSON to a REST API endpoint?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I send a POST request to API?

To make a POST request to an API endpoint, you need to send an HTTP POST request to the server and specify a Content-Type request header that specifies the data media type in the body of the POST request. The Content-Length header indicates the size of the data in the body of the POST request.


1 Answers

I edited your code and it works well.

A [FromBody] attribute specifies that an action parameter comes only from the entity body of the incoming HTTPRequestMessage.

public class TestApiController : ApiController
    {
        // POST api/<controller>
        [HttpPost]
        public HttpResponseMessage Post([FromBody]string value)
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("POST: Test message: " + value)
            };
        }

    }

function sendRequest() {
    var Test = { "Name": "some name" };

    $.ajax({
        type: "POST",
        url: "api/TestApi",
        data: { '': JSON.stringify(Test) }
    }).done(function (data) {
        alert(data);
    }).error(function (jqXHR, textStatus, errorThrown) {
        alert(jqXHR.responseText || textStatus);
    });
}
like image 93
Alex Nguyen Avatar answered Oct 06 '22 00:10

Alex Nguyen