Reputation: 20234
I am calling a C# WebAPI with the following request:
Request URL: https://devserver/myapp/api/SaveSettings?debug=0
Request Method:POST
Status Code:202 Accepted
Request Headers
...
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
...
Form Data:
config:{"test":"test12"}
Response Headers:
...
Server: Microsoft-IIS/7.5
...
The WebAPI application code is
public class SaveSettingsController : ApiController
{
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
public HttpResponseMessage PostComplex(MyModel update)
{
if (ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.Accepted,update.config.test);
}
}
}
While the Status Code is sent correctly (which is why I came to believe that this code is really executed), the content is always null, and I don't know why. I also tried a model with config set to type string, and
return Request.CreateResponse(HttpStatusCode.Accepted,update.config);
but to no avail: it still returns null.
Why is this? What am I doing wrong?
Upvotes: 2
Views: 1893
Reputation: 57989
You request content-type is application/x-www-form-urlencoded
, but you are sending Json data. Either change your content-type to application/json
or change the format of the request body data.
Upvotes: 1
Reputation: 2729
You dont have to create a response and all that complicated stuff, just return any value, it gets jsonized
Upvotes: 1
Reputation: 696
If you have a post parameter in web api you decorate it with the [FromBody] attribute like below:
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
public HttpResponseMessage PostComplex([FromBody] MyModel update)
{
if (ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.Accepted,update.config.test);
}
}
Upvotes: 2