Csharp/C#教程:将JSON HttpContent发布到ASP.NET Web API分享


将JSON HttpContent发布到ASP.NET Web API

我有一个托管的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 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 GetInventoryByLocationIDAndCode([FromBody] int id, string code) { ... } 

有关更多信息, 请参阅文档 。

上述就是C#学习教程:将JSON HttpContent发布到ASP.NET Web API分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1012866.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐