邮政JSON HttpContent到的ASP.NET Web API [英] Post JSON HttpContent to ASP.NET Web API

查看:300
本文介绍了邮政JSON HttpContent到的ASP.NET Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API托管,并且可以访问HTTP GET请求就好了,我现在需要几个参数传递到像这样一个PostAsync要求:

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:

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未找​​到结果。

This call is returning a 404 Not Found result.

服务器端API动作看起来像这样:

The server side API action looks like so:

[HttpPost]
public List<ItemInLocationModel> GetInventoryByLocationIDAndCode(int id, string code) {
...
}

和只是为了确认在Web API我的路线是这样的:

And just to confirm my route on the Web API looks like this:

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

我以为我传递JSON HttpContent跨错误,为什么会变成这样返回状态404?

I assume I'm passing the JSON HttpContent across incorrectly, why would this be returning status 404?

推荐答案

您收到404的原因是因为该框架没有找到要执行给您的请求的方法。默认情况下,网络API使用下列规则结合的方法参数:

The reason you're receiving a 404 is because the framework didn't find a method to execute given your request. By default, Web API uses the following rules to bind parameters in methods:


  • 如果该参数是一个简单的类型,网络API将尝试从URI中的价值。简单类型包括.NET基本类型(int,布尔,双精度等),再加上时间跨度,日期时间,GUID小数和字符串,以及任何类型的类型转换器,可以从一个字符串转换。 (更多关于类型转换器的更新版本。)

  • 对于复杂类型,网络API尝试读取邮件正文中的价值,使用的媒体类型格式化

  • If the parameter is a "simple" type, Web API tries to get the value from the 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. (More about type converters later.)
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

由于这些规则,如果你想从POST身体参数绑定只需在型号前添加一个 [FromBody] 属性:

Given those rules, if you want to bind the parameter from the POST body simply add a [FromBody] attribute in front of the type:

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

有关详细信息,<一个href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api\"相对=nofollow>请参阅文档。

这篇关于邮政JSON HttpContent到的ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆