1

I'm a little confused as to how AngularJS is POSTing data to my WebAPI controller. Normally, when I would POST data from AngularJS to an MVC controller, I would do something like this:

var data = { "value": "some string" };
$http.post('/api/products', { data
}).success(function () {...

However, in the WebAPI controller, the string value is always coming back as null.

Do I need to post the data a little differently when passing data to a web api controller?

Here is the method in my controller:

    [HttpPost]
    public void Post([FromBody]string value)
    {
     .....
    }

edit Not sure if this helps, but this is the header from Fiddler:

POST http://localhost:58167/api/products/ HTTP/1.1 Host: localhost:58167 Connection: keep-alive Content-Length: 11 Accept: application/json, text/plain, / Origin: http://localhost:58167 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36 Content-Type: application/json;charset=UTF-8 Referer: http://localhost:58167/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8

some string

Anonymous
  • 1,978
  • 2
  • 28
  • 37

1 Answers1

1

Change your Web API to accept a complex type (model) instead of a string.

public class Product
{
    public string Value {get; set;}
}

[HttpPost]
public void Post([FromBody]Product product)
{
    Debug.WriteLine(product.Value);
}
mason
  • 31,774
  • 10
  • 77
  • 121