2016-07-18 65 views
1

我試圖將一個字符串發送到我的網頁API像這樣:發送JSON字符串作爲一個POST到asp.net網頁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

你應該裝點[FromBody]屬性爲之後的參數不會採取從url值我懷疑

+0

嗯我用FromBody嘗試過,仍然爲空。如果發送一串json,content-type應該是application/json嗎? –

0

看起來像您選擇發佈到API /產品,而不是API /產品/過濾器。 該方法的簽名應該與Vidas所說的使用from body屬性一樣,但發佈到正確的url。

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

雖然路線沒有特別需要,但它可以幫助您指定您正在使用的網址!

+0

對不起我apolgize。在產品控制器的頂部,我指定了api/controllerName。 –

+0

我的觀察是基於你的getproducts方法,但看起來像你得到它在最後排序是主要的東西 –

相關問題