Post JSON string to WEB API

2019-02-09 11:12发布

问题:

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?

回答1:

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);
    });
}


回答2:

Either treat the POST request as a generic HTTP request, and manually parse the body:

public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
    var jsonString = await request.Content.ReadAsStringAsync();

    // deserialize the string, or do other stuff

    return new HttpResponseMessage(HttpStatusCode.OK);
}

Or use a generic JToken, and let the serializer do the rest:

public HttpResponseMessage Post([FromBody] JToken model)
{
    DoStuff(model);

    var myField = model["fieldName"];

    return new HttpResponseMessage(HttpStatusCode.OK);
}

Notes: this way you do not need to alter client-side code, because you are still POSTing json data, not a generic string, which is semantically the right choice if you expect your client to post serialized JSON objects.

References:

http://bizcoder.com/posting-raw-json-to-web-api