C# – How to call a Post api with multiple parameters

asp.net-web-apichttpclient

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)

Best Answer

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;