Reputation: 1030
I'm trying to make a web api using the new .NET Core. But having some trouble using the the [HttpPost]
. When I use postman, it doesn't return anything. Also when I put a breakpoint on the return line it's never hit.
This is my method in the controller:
// POST api/values
[HttpPost]
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "value1", "value2" };
}
The GET method is working:
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
It returns a Json value and when I place a breakpoint it hits.
I think I have to add something somewhere else to map the post to this method, but I can't figure out what.
This is the Post code generated in Postman:
POST /api/values HTTP/1.1
Host: localhost:60228
Content-Length: 0
Cache-Control: no-cache
Postman-Token: 295f7c89-f5a8-d6cd-d679-ae907b010550
firstName:jantje
Upvotes: 2
Views: 2017
Reputation: 201
I've found myself in the same situation and the reason was that i send text/plain request instead of application/json request.
After this change I was able to send a simple string to the HttpPost action. Before the change no breakpoint was hit too.
I've tried it with ValuesController from the WebAPI example and it runs too.
Upvotes: 0
Reputation: 15485
Try to post JSON data to your controller action and use a model class to bind the values. I assume the simple string cannot be parsed by the JSON or XML formatters that are used by ASP.NET Core by default.
So this will probably work:
[HttpPost]
public IActionResult Post([FromBody]DataModel model)
{
return Ok();
}
public class DataModel {
public string FirstName {get; set;}
}
with this JSON data
{
firstName: "jantje"
}
Upvotes: 2