Home > other >  How to pass integer array as request body while calling .Net core web api post method
How to pass integer array as request body while calling .Net core web api post method

Time:03-21

I am trying to call one of my APIs POST method from my client code using httpclient. The problem is that I want to pass array of integer(ids) as request body as per my destination APIs POST method, but I am not able to call this method using my source code.

Could anyone help me ?

Destination code:

public IActionResult GetByIds([FromBody] int[] ids)
{
    try
    {
        var collterals = _collateralRepository.GetCollateralsByIds(ids);
        return Ok(collterals);
    }
    catch (Exception)
    {

        throw;
    }
}

Source Code:

int[] ids = outputsummary.Select(x => x.Collateral_Id).ToArray();
var data = new StringContent(JsonConvert.SerializeObject(ids), Encoding.UTF8, "application/json");
var collateralClient = _httpClientFactory.CreateClient("CollateralClient");
var response = await collateralClient.PostAsync("Collateral/GetByIds", data);

CodePudding user response:

It seems that WEB API is not able to get the data correctly since it does not deal with multiple posted content values. The best way for your case would be to create a Model class that will hold your int[] and then you can POST it to your API.

public class MyIDModel
{
    public int[] ids{ get; set; }
}

So your source code will be:

int[] ids = outputsummary.Select(x => x.Collateral_Id).ToArray();
MyIDModel mymodel=new MyIDModel();
mymodel.ids=ids;
var data = new StringContent(JsonConvert.SerializeObject(mymodel), Encoding.UTF8, "application/json");
var collateralClient = _httpClientFactory.CreateClient("CollateralClient");
var response = await collateralClient.PostAsync("Collateral/GetByIds", data);

Your destination code will remain the same.

CodePudding user response:

I don't know why you can not send data without wraping using json, I tested your code using common httpclient and it is working properly at my mashine. The problem coud be in your named client _httpClientFactory.CreateClient("CollateralClient");

But there is another way if you want to sent an array without wraping it in a viewmodel, you can try this code that is using application/x-www-form-urlencoded content

    int[i] ids=..your code
    int counter = 0;
    var values = new List<KeyValuePair<string, string>>();

    foreach (int i in ids)
    {
        values.Add(new KeyValuePair<string, string>("ids["   counter.ToString()   "]", i.ToString()));
        counter  ;
    }
    
    var content = new FormUrlEncodedContent(values);
    
    var response = await collateralClient.PostAsync("Collateral/GetByIds", content);

and remove [frombody]

public IActionResult GetByIds(int[] ids)    
  • Related