Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post JSON HttpContent to ASP.NET Web API

I have an ASP.NET Web API hosted and can access http get requests just fine, I now need to pass a couple of parameters to a PostAsync request like so:

var param = Newtonsoft.Json.JsonConvert.SerializeObject(new { id=_id, code = _code });
HttpContent contentPost = new StringContent(param, Encoding.UTF8, "application/json");

var response = client.PostAsync(string.Format("api/inventory/getinventorybylocationidandcode"), contentPost).Result;

This call is returning a 404 Not Found result.

The server side API action looks like so:

[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode(int id, string code) {
...
}

And just to confirm my route on the Web API looks like this:

config.Routes.MapHttpRoute(
            name: "DefaultApiWithAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
);

I assume I'm passing the JSON HttpContent across incorrectly, why would this be returning status 404?

like image 418
Leigh Avatar asked Jun 08 '14 18:06

Leigh


People also ask

How do I post JSON data to API using C#?

To post JSON to a REST API endpoint using C#/. NET, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the C#/. NET POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

What is HTTP POST in Web API?

The HTTP POST request is used to create a new record in the data source in the RESTful architecture. So let's create an action method in our StudentController to insert new student record in the database using Entity Framework. The action method that will handle HTTP POST request must start with a word Post.


1 Answers

The reason you're receiving a 404 is because the framework didn't find a method to execute given your request. By default, Web API uses the following rules to bind parameters in methods:

  • If the parameter is a “simple” type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

Given those rules, if you want to bind the parameter from the POST body simply add a [FromBody] attribute in front of the type:

[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode([FromBody] int id, string code) {
...
}

For more information please see the documentation.

like image 146
Justin Helgerson Avatar answered Sep 19 '22 15:09

Justin Helgerson