简体   繁体   English

将JSON HttpContent发布到ASP.NET Web API

[英]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使用以下规则绑定方法中的参数:

  • If the parameter is a “simple” type, Web API tries to get the value from the URI. 如果参数是“简单”类型,则Web API会尝试从URI获取值。 Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. 简单类型包括.NET基元类型(int,bool,double等),以及TimeSpan,DateTime,Guid,decimal和string,以及具有可以从字符串转换的类型转换器的任何类型。 (More about type converters later.) (稍后将详细介绍类型转换器。)
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter . 对于复杂类型,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM