如何使用HttpClient调用具有多个参数的Post方法?
我使用以下代码和一个参数:
var paymentServicePostClient = new HttpClient();
paymentServicePostClient.BaseAddress =
new Uri(ConfigurationManager.AppSettings["PaymentServiceUri"]);
PaymentReceipt payData = SetPostParameter(card);
var paymentServiceResponse =
paymentServicePostClient.PostAsJsonAsync("api/billpayment/", payData).Result;
我需要添加另一个参数userid。如何将参数与'postData'一起发送?
WebApi POST方法原型:
public int Post(PaymentReceipt paymentReceipt,string userid)
答案 0 :(得分:5)
只需在包含这两个属性的Web Api控制器上使用视图模型。所以而不是:
public HttpresponseMessage Post(PaymentReceipt model, int userid)
{
...
}
使用:
public HttpresponseMessage Post(PaymentReceiptViewModel model)
{
...
}
PaymentReceiptViewModel
显然会包含userid
属性。然后你就可以正常调用这个方法了:
var model = new PaymentReceiptViewModel()
model.PayData = ...
model.UserId = ...
var paymentServiceResponse = paymentServicePostClient
.PostAsJsonAsync("api/billpayment/", model)
.Result;
答案 1 :(得分:4)
UserId
应该在查询字符串中:
var paymentServiceResponse = paymentServicePostClient
.PostAsJsonAsync("api/billpayment?userId=" + userId.ToString(), payData)
.Result;
答案 2 :(得分:3)
在我的情况下,我现有的ViewModel与我想发布到我的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;
...
}
(我很想知道这种方法的一些反馈。这绝对是代码少得多。)