10

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?

sideshowbarker
89k30 gold badges218 silver badges215 bronze badges
asked Apr 12, 2016 at 8:03
7
  • try data: {model :JSON.stringify(Test)} Commented Apr 12, 2016 at 8:20
  • this gives me a Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource error message Commented Apr 12, 2016 at 8:28
  • Don't JSON.stringify. Use Data: {value: Test} and in your controller ([FromBody]string Test). That should return a string. Commented Apr 12, 2016 at 8:55
  • Don't use JOSN contentType. Just post a string with json format then use JsonConvert.DeserializeObject to convert it to your expected object. Commented Apr 12, 2016 at 9:02
  • @MarcusH tried but I still get a null value Commented Apr 12, 2016 at 9:33

2 Answers 2

12

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);
 });
}
Town
14.9k3 gold badges50 silver badges72 bronze badges
answered Apr 12, 2016 at 11:39
2
9

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

answered Apr 12, 2016 at 14:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.