Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Post api with multiple parameters

How can i call a Post method with multiple parameters using HttpClient?

I am using the following code with a single parameter:

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

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

I need to add another parameter userid. How can i send the parameter along with the 'postData'?

WebApi POST method prototype:

public int Post(PaymentReceipt paymentReceipt,string userid)
like image 453
NewBie Avatar asked Nov 30 '22 21:11

NewBie


2 Answers

Simply use a view model on your Web Api controller that contains both properties. So instead of:

public HttpresponseMessage Post(PaymentReceipt model, int userid)
{
    ...
}

use:

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

where the PaymentReceiptViewModel will obviously contain the userid property. Then you will be able to call the method normally:

var model = new PaymentReceiptViewModel()
model.PayData = ...
model.UserId = ...
var paymentServiceResponse = paymentServicePostClient
    .PostAsJsonAsync("api/billpayment/", model)
    .Result;
like image 83
Darin Dimitrov Avatar answered Dec 05 '22 08:12

Darin Dimitrov


UserId should be in query string:

var paymentServiceResponse = paymentServicePostClient
                            .PostAsJsonAsync("api/billpayment?userId=" + userId.ToString(), payData)
                            .Result;
like image 21
cuongle Avatar answered Dec 05 '22 10:12

cuongle