CikLinas
CikLinas

Reputation: 242

HttpClient POST multiple objects/variables

I'm using HttpClient to connect .NET project with my Web API.

Thing is, that i can't make it work when sending multiple variables or objects. With one parameter i do like this:

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost/");
            client.DefaultRequestHeaders.Accept.Clear();

            int systemId = 24;

            var response = client.PostAsJsonAsync("api/method/{id}", systemId).Result;
            if (response.IsSuccessStatusCode)
            {
                // Do
            }
            else
                // DO
        }

With several variables, i can't make ir work. I don't get how to send several variables. It may be one Object and Byte[] or two integers and similar. Uri would be like: "Api/Method/{SystemId}/{Id}.

Maybe [FromBody] attribute could help me in this solution ? And how do i make it work?

Thanks in advance.

Upvotes: 0

Views: 6377

Answers (1)

Tiago B
Tiago B

Reputation: 2065

Assuming you have the following Route:

routes.MapRoute(
                name: "MyAPIRoute",
                url: "Api/Method/{SystemId}/{Id}"

            );

You can call it, binding the SystemId and Id parameter with Query String:

using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost/");
        client.DefaultRequestHeaders.Accept.Clear();

        int systemId = 24;
        int id = 45;
        string queryString = "SystemId="+systemId+"&Id="+id;

        var response = client.PostAsJsonAsync("api/method/",queryString).Result;
        if (response.IsSuccessStatusCode)
        {
            // Do
        }
        else
            // DO
    }

Upvotes: 1

Related Questions