将JSON字符串作为POST发送到asp.net web api
本文关键字:asp net web api 字符串 JSON POST | 更新日期: 2023-09-27 17:57:28
我正试图向我的web 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;
}
在我的产品控制器中,我的操作方法如下:
// POST: api/products/filter
[HttpPost("filter")]
public IList<Product> Filter(string filter)
{
}
由于某种原因,筛选器参数一直为null。有什么想法吗?
您应该用[FromBody]属性装饰参数,因为post不会从我怀疑的url中获取值
看起来你发布的是api/products,而不是api/products/filter。方法的签名应该是Vidas所说的from body属性,但要发布到正确的url。
[HttpPost]
[Route("api/products/filter")
Public ilist<product> Filter([FromBody] string filter)
{...}
虽然路由不是特别必要的,但它可以帮助您指定正在使用的url!