2013-02-28 37 views
0

如何使用HttpClient調用具有多個參數的Post方法?如何調用具有多個參數的Post api

我使用下面的代碼用一個參數:

var paymentServicePostClient = new HttpClient(); 
paymentServicePostClient.BaseAddress = 
        new Uri(ConfigurationManager.AppSettings["PaymentServiceUri"]); 

PaymentReceipt payData = SetPostParameter(card); 
var paymentServiceResponse = 
    paymentServicePostClient.PostAsJsonAsync("api/billpayment/", payData).Result; 

我需要添加其他參數的用戶ID。我怎樣才能發送參數以及'postData'?

的WebAPI POST方法的原型:

public int Post(PaymentReceipt paymentReceipt,string userid) 
+0

如何從您的Web API的行動? – 2013-02-28 11:45:51

+0

'來自webapi的動作'是指? – NewBie 2013-02-28 11:48:29

+0

你想要你的POST請求調用Web Api的方法 – 2013-02-28 11:49:31

回答

3

UserId應該在查詢字符串發佈到我的WebAPI。所以,我沒有創建一組全新的模型類,而是發佈了一個匿名類型,並讓我的Controller接受一個動態類型。

var paymentServiceResponse = paymentServicePostClient.PostAsJsonAsync("api/billpayment/", new { payData, userid }).Result; 



public int Post([FromBody]dynamic model) 
{ 
    PaymentReceipt paymentReceipt = (PaymentReceipt)model.paymentReceipt; 
    string userid = (string)model.userid; 

    ... 

} 

(我很好奇地聽到這種方法的一些反饋。這肯定少了很多代碼。)

5

只是一個包含兩個屬性的網絡API控制器上使用視圖模型。因此,而不是:

​​

使用:

public HttpresponseMessage Post(PaymentReceiptViewModel model) 
{ 
    ... 
} 

其中PaymentReceiptViewModel顯然包含userid財產。然後,你將能夠調用正常的方法:與我想要的數據非常漂​​亮

var paymentServiceResponse = paymentServicePostClient 
          .PostAsJsonAsync("api/billpayment?userId=" + userId.ToString(), payData) 
          .Result; 
+0

是這樣嗎?帖子不能再有一個參數? – NewBie 2013-02-28 11:56:38

+0

這是實現它的正確方法。 – 2013-02-28 13:12:51

+1

這應該是被接受的答案imo,目前接受的只適用於簡單類型 – reggaeguitar 2015-06-04 16:41:18

2

在我的情況我現有的ViewModels不排隊:

var model = new PaymentReceiptViewModel() 
model.PayData = ... 
model.UserId = ... 
var paymentServiceResponse = paymentServicePostClient 
    .PostAsJsonAsync("api/billpayment/", model) 
    .Result; 
+0

真棒解決方案。使用'[FromBody]'和'[FromUri]'非常簡單。 – thomasb 2017-02-28 17:01:02

相關問題