我托管了一个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;
该调用返回404 Not Found结果。
服务器端API操作如下所示:
[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode(int id, string code) {
...
}
只是为了确认我在Web API上的路由,如下所示:
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我假设我错误地传递了JSON HttpContent,为什么会返回状态404?
您收到404的原因是因为框架没有找到根据您的请求执行的方法。默认情况下,Web API使用以下规则来绑定方法中的参数:
给定这些规则,如果要绑定POST正文中的参数,只需[FromBody]
在类型前面添加一个属性:
[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode([FromBody] int id, string code) {
...
}
有关更多信息,请参见文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句