Home > Mobile >  API POST method passes all the variables as null C# Forms
API POST method passes all the variables as null C# Forms

Time:01-16

I have a WEB API created with .NET and I have a few POST and GET methods that I want to use in another C# Windows Form project. The GET methods work correctly but for some reason I can't get the POST method to work as it doesn't pass the correct variables.

I have a constructor that sets the default url

client.BaseAddress = new Uri("http://localhost:7101/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

so I have this post method and the api gets the call but both the variables are equal to 0 (in the API), while in this method they are with different values (the correct ones).

Here is the API:

[HttpPost]
[Route("UpdatePercentage")]
public void UpdatePercentage(int playerid, int percentage)
{
    ...
}

Here is how I have used it:

var userid = 2;
var percentageText = 21;
var response = await client.PostAsJsonAsync("UpdatePercentage",
    (userid, percentageText));

CodePudding user response:

You have to fix two things:

  • You are using tuple; use an anonymous type instead.
  • You are passing wrong parameter names.

So fix the code like this:

var playerid = 2;
var percentage = 21;
var response = await client.PostAsJsonAsync("UpdatePercentage",
    new {playerid , percentage});

OR

var userid = 2;
var percentageText = 21;
var response = await client.PostAsJsonAsync("UpdatePercentage",
    new {playerid = userid , percentage = percentageText});

Example:

Assuming you have the following variables:

var x= 1;
var y = "something";

Then:

  • If you pass (x, y) as parameter, it will be json serialized to {"Item1":1,"Item2":"something"} which is not expected by the API.
  • If you pass new {x, y} as parameter, it will be json serialized to {"x":1,"y":"something"} which is expected by the API.
  • Related