I’m trying to send some basic POST data between an MVC and a .NET Core API.
When I post the data, I get this error:
The remote server returned an error: (400) Bad Request
My Controller:
[HttpPost]
[Route ("simple")]
public int PostSimple([FromBody] string value)
{
return 0;
}
My POST code to this Controller:
string url = "my.api/Controller/Simple";
var client = new WebClient();
client.Headers.Add("Content-Type:application/json");
string data = "some data I want to post";
byte[] postArray = Encoding.ASCII.GetBytes(data);
var response = client.UploadData(encoded, "POST", postArray);
This happens only when I use [FromBody]
When I remove it, I can get to the web method, but I cannot see the POSTed data.
Any ideas would be appreciated.
>Solution :
You explicitly tell your api controller to except json format (header : Content-Type:application/json). You then have to provide a body that follows the rule.
A raw string isn’t json, that why you get back this 400 bad request.
In order to fix that, you first need to create a class to map the request json
public class MyRequest
{
public string Value { get; set; }
}
then use it in your controller
[HttpPost]
[Route ("simple")]
public int PostSimple([FromBody] MyRequest request)
{
// access the value using request.Value
}
Finally, send your controller a json body
string data = "{\"value\" : \"some data I want to post\"}";
byte[] postArray = Encoding.ASCII.GetBytes(data);
var response = client.UploadData(encoded, "POST", postArray);