c# - Post JSON HttpContent to ASP.NET Web API -


i have asp.net web api hosted , can access http requests fine, need pass couple of parameters postasync request 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 returning 404 not found result.

the server side api action looks so:

[httppost] public list<iteminlocationmodel> getinventorybylocationidandcode(int id, string code) { ... } 

and confirm route on web api looks this:

config.routes.maphttproute(             name: "defaultapiwithaction",             routetemplate: "api/{controller}/{action}/{id}",             defaults: new { id = routeparameter.optional } ); 

i assume i'm passing json httpcontent across incorrectly, why returning status 404?

the reason you're receiving 404 because framework didn't find method execute given request. default, web api uses following rules bind parameters in methods:

  • if parameter “simple” type, web api tries value uri. simple types include .net primitive types (int, bool, double, , forth), plus timespan, datetime, guid, decimal, , string, plus type type converter can convert string. (more type converters later.)
  • for complex types, web api tries read value message body, using media-type formatter.

given rules, if want bind parameter post body add [frombody] attribute in front of type:

[httppost] public list<iteminlocationmodel> getinventorybylocationidandcode([frombody] int id, string code) { ... } 

for more information please see documentation.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -