将JSON HttpContent发布到ASP.NET Web API

Lei*_*igh 12 c# httpclient asp.net-web-api httpcontent

我有一个托管的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;
Run Code Online (Sandbox Code Playgroud)

此调用返回404 Not Found结果.

服务器端API操作如下所示:

[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode(int id, string code) {
...
}
Run Code Online (Sandbox Code Playgroud)

只是为了确认我在Web API上的路由如下所示:

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

我假设我正在错误地传递JSON HttpContent,为什么这将返回状态404?

Jus*_*son 5

您收到404的原因是因为框架没有根据您的请求找到执行方法.默认情况下,Web API使用以下规则绑定方法中的参数:

  • 如果参数是"简单"类型,则Web API会尝试从URI获取值.简单类型包括.NET基元类型(int,bool,double等),以及TimeSpan,DateTime,Guid,decimal和string,以及具有可以从字符串转换的类型转换器的任何类型.(稍后将详细介绍类型转换器.)
  • 对于复杂类型,Web API尝试使用媒体类型格式化程序从邮件正文中读取值.

根据这些规则,如果要从POST主体绑定参数,只需[FromBody]在类型前面添加一个属性:

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

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