【问题标题】:Post JSON HttpContent to ASP.NET Web API将 JSON HttpContent 发布到 ASP.NET Web API
【发布时间】:2014-06-08 18:09:18
【问题描述】:

我有一个托管的 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?

【问题讨论】:

    标签: c# asp.net-web-api httpclient httpcontent


    【解决方案1】:

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

    • 如果参数是“简单”类型,Web API 会尝试从 URI 中获取值。简单类型包括 .NET 基本类型(int、bool、double 等),加上 TimeSpan、DateTime、Guid、decimal 和 string,以及任何具有可以从字符串转换的类型转换器的类型。 (稍后会详细介绍类型转换器。)
    • 对于复杂类型,Web API 尝试使用 media-type formatter 从消息正文中读取值。

    鉴于这些规则,如果您想绑定 POST 正文中的参数,只需在类型前添加 [FromBody] 属性:

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

    欲了解更多信息please see the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      相关资源
      最近更新 更多