Reputation: 5211
I used the template in Visual Studio 2017 for asp.net core 2.0/react.js but could not manage to post data in the body.
The id
from the url is filled correctly, but the string from the body is null
.
I'm using IIS Express if it matters.
My code so far:
Server part:
[Produces("application/json")]
[Route("api/Parts")]
public class PartsController : Controller
{
// POST: api/Parts
[HttpPost("{id}")]
public void Post(int id, [FromBody]string value)
{
// breakpoint is hit.
// id is set.
// if I change "string value" to "dynamic value" I get an JObject.
}
}
Client part:
private sendUpdates() {
var payload = { "value": "2"}
fetch('api/Parts/5',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
}
The request looks fine in the browser debug:
Upvotes: 5
Views: 9362
Reputation: 43
Core API controller
[Route("api/[controller]")]
public class TestingController : Controller
{
[HttpPost("test")]
public IActionResult Test(string pl)
{
if (pl == null)
{
return Ok();
}
PL plobj = JsonConvert.DeserializeObject<PL>(pl);
return Ok($"Test Test a=={plobj.a} b=={plobj.b}");
}
}
C# Class to serialize
public class PL
{
public string a { get; set; }
public string b { get; set; }
}
ReactJs Part
constructor(props) {
super(props);
this.state = { text: "", loading: true};
var PL = {
a: 1,
b: 2
};
var data = new FormData();
data.append("PoLos", JSON.stringify(PL));
fetch('api/Testing/test',
{
method: "POST",
body: data
}).
then(response => response.text())
.then(data => {
this.setState({ text: data, loading: false });
});
}
I have to Note: Name in appending data in React part must be same AS name of variable in Core controller (ignoring case)
Upvotes: 1