[英]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: 我有一个托管的ASP.NET Web API,可以正常访问http get请求,我现在需要将一些参数传递给PostAsync请求,如下所示:
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. 此调用返回404 Not Found结果。
The server side API action looks like so: 服务器端API操作如下所示:
[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode(int id, string code) {
...
}
And just to confirm my route on the Web API looks like this: 只是为了确认我在Web API上的路由如下所示:
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? 我假设我正在错误地传递JSON HttpContent,为什么这将返回状态404?
The reason you're receiving a 404 is because the framework didn't find a method to execute given your request. 您收到404的原因是因为框架没有根据您的请求找到执行方法。 By default, Web API uses the following rules to bind parameters in methods:
默认情况下,Web API使用以下规则绑定方法中的参数:
Given those rules, if you want to bind the parameter from the POST body simply add a [FromBody]
attribute in front of the type: 根据这些规则,如果要从POST主体绑定参数,只需在类型前面添加一个
[FromBody]
属性:
[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode([FromBody] int id, string code) {
...
}
For more information please see the documentation . 有关更多信息, 请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.