Like many others (e.g. the 36 answers here) when I post a string to ASP.Net Core the value is always null. I tried [FromBody]
but that results in my calls receiving a 400 error. Eventually I found this 'solution', which works:
[Route("api/[controller]")]
[ApiController]
public class ScoresController : ControllerBase
{
[HttpPost]
public void Post(string value)
{
# 'value' is null, so ...
Request.EnableRewind();
var body = "";
using (var reader = new StreamReader(Request.Body))
{
Request.Body.Seek(0, SeekOrigin.Begin);
body = reader.ReadToEnd();
}
value = body;
# Now 'value' is correct, use it ...
}
}
Here is an example of the value I post from the client (Python, using 'requests'):
'{"Username": "TestUserNumber5", "Email": "testuser5@nowhere.com", "PasswordHash": 5}'
and once I have retrieved it from the body in ASP.Net Core it looks like this:
"{\"Username\": \"TestUserNumber5\", \"Email\": \"testuser5@nowhere.com\", \"PasswordHash\": 5}"
I do not explicitly set the content-type, here's the Python code I use to post:
def add_score(score):
score_json = json.dumps(score)
response = requests.post(url+"scores/", data=score_json, verify=False)
return response.ok
Reading the body a second time seems very hacky. Why do I need it?