2013-02-28 80 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