【问题标题】:Sending a string of JSON as a POST to asp.net web api [duplicate]将 JSON 字符串作为 POST 发送到 asp.net web api [重复]
【发布时间】:2016-11-21 14:23:02
【问题描述】:

我正在尝试像这样向我的网络 API 发送一个字符串:

public IList<Product> GetProducts(string myString)
{
    IList<Product> retVal = null;
    using (var client = GetClient())
    {
        HttpContent httpContent = new StringContent(myString, Encoding.UTF8, "application/json");

        // HTTP POST
        HttpResponseMessage response = client.PostAsync("api/products", httpContent).Result;
    }
    return retVal;
}

在我的 ProductsController 中,我的操作方法如下所示:

// POST: api/products/filter
[HttpPost("filter")]
public IList<Product> Filter(string filter)
{

}

由于某种原因,过滤器参数一直为空。任何想法为什么?

【问题讨论】:

    标签: c# asp.net json asp.net-web-api asp.net-web-api2


    【解决方案1】:

    您应该使用 [FromBody] 属性来装饰参数,因为我怀疑帖子不会从 url 中获取值

    【讨论】:

    • 嗯,我用 FromBody 试过了,但仍然为空。如果发送一个json字符串,content-type应该是application/json吗?
    【解决方案2】:

    看起来您正在发布到 api/products,而不是 api/products/filter。 该方法的签名应如 Vidas 所说的 from body 属性,但发布到正确的 url。

    [HttpPost]
    [Route("api/products/filter")
    Public ilist<product>  Filter([FromBody] string filter)
    {...}
    

    虽然路由不是特别需要,但它可以帮助您指定正在使用的 url!

    【讨论】:

    • 对不起,我很抱歉。在产品控制器的顶部,我指定了 api/controllerName。
    • 我的观察是基于你的 getproducts 方法,但看起来你最终得到了排序,这是主要的事情
    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2018-08-21
    • 1970-01-01
    • 2016-08-02
    • 2019-04-11
    • 2020-11-11
    相关资源
    最近更新 更多