2

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.

Update: The post request

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
2
  • please show us the Post request Commented Nov 21, 2016 at 13:03
  • I've added the post request to the question Commented Nov 21, 2016 at 13:07

2 Answers 2

2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

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.