Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting 404 Bad Request when using [FromBody] annotation in API method

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading