zoidbergi zoidbergi - 3 months ago 26
AngularJS Question

Http.post from Angular 2 to ASP.NET ApiController

ASP.NET

[HttpPost]
[Route("apitest")]
public string apitest([FromBody]string str)
{
Console.Writeline(str); // str is always null
return null;
}


Angular 2:

var creds = "str='testst'" ;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

http.post('http://localhost:18937/apitest', creds, {
headers: headers
})
.map(res => res.json())
.subscribe(
(res2) => {
console.log('subsribe %o', res2)
}
);


I also tried
creds = {"str":"test"};
without headers
JSON.stringify()
etc. without success. How do I Post data to ASP.NET?

Answer
var creds = {
   str: 'testst'
};

$http.post('http://localhost:18937/apitest', JSON.stringify(creds));

No changes in Web API controller and it should work.

Comments