将一串JSON作为POST发送到asp.net web api

时间:2016-07-18 20:55:35

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

我正在尝试将字符串发送到我的网络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)
{

}

由于某种原因,过滤器参数保持为空。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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

虽然路线不是特别必要,但它可以帮助您指定您正在使用的网址!