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

Time:05-25

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.

CodePudding user response:

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);

CodePudding user response:

Your variable "data" should contain a JSON string.

var response = client.UploadData(url, "POST", postArray);

CodePudding user response:

You get this error because you actually send invalid data. What the server expects (from body) is this:

{
  "value" : "some data I want to post"
}

What you send is just a string, nothing else; this will result in an invalid request. Within your POST code change your method to something like this (pseudo-coded):

var stringedClass = new MyClass() { value = "This is the string" };
var message = new HttpRequestMessage(HttpMethod.Post, "url");
message.Content = new StringContent(JsonConvert.SerializeObject(stringedClass), Encoding.UTF8, "application/json");
using (var response = await _client.SendAsync(msg).ConfigureAwait(false))
        {
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(response.ToString());
            }
        }
  • Related