Ryan L.
Ryan L.

Reputation: 103

Post JSON string to RESTful API using C# ASP.NET MVC async

I'm having trouble with sending a post request to a RESTful API. The API expects the following JSON body:

{ "APIKey":"String content", "ID":"String content", "Data":"String content", "TokenScheme":0 }

I'd like for it to use async but this is a first for me and I'm having issues just handling the return string. I'd just like to know how to send the string data to the view and I'll get it from there.

Here is what I'm trying to use but the browser just spins and spins.

public async Task<string> RunAsync()
{
    using (var client = new HttpClient())
    {
        // TODO - Send HTTP requests
        client.BaseAddress = new Uri("https://test-api.com/Services.svc/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        string APIKey, ID, Data, Scheme;

        // HTTP POST
        string[] jsonRequest = { APIKey = "", ID = "", Data = "teststring", Scheme = "0" };
        //alt option IHttpActionResult 
        HttpResponseMessage response = await client.PostAsJsonAsync("REST/Service", jsonRequest);
        if (response.IsSuccessStatusCode)
        {
            Debug.WriteLine(@"             successful.");
            return "";
        }
        else
        {
            Debug.WriteLine(@"             Failed.");
            return "";
        }
    }
}

Upvotes: 1

Views: 1592

Answers (2)

Fran
Fran

Reputation: 6520

the json should not be declared as a string[]. That will create a Json like

[{ "APIKey":"String content"}, 
{"ID":"String content"}, 
{"Data":"String content"}, 
{"TokenScheme":0 }]

you want to just create an anonymous object and pass it to the PostAsJsonAsync

like this

var anonymousObject = new { APIKey = "", ID = "", Data = "teststring", TokenScheme = "0" };

HttpResponseMessage response = await client.PostAsJsonAsync("REST/Service", anonymousObject);

PostAsJsonAsync will handle serializing your object to Json for you.

Upvotes: 1

RomHi
RomHi

Reputation: 31

You are mixing two concepts here. A string array does not have property name or indexors, only a set of strings. You mistakenly seem to do that by also assigning values to variables on the same line where you are creating the array.

So this line:

string[] jsonRequest = { APIKey = "", ID = "", Data = "teststring", Scheme = "0" };

Actually is doing this:

APIKey = "";
ID = "";
Data = "teststring";
Scheme = "0";

string[] jsonRequest = { "", "", "teststring", "0" }; // String array without property names

Easiest way to fix your problem is to use an anonymous type instead of a string[]

var jsonRequest = new { APIKey = "", ID = "", Data = "teststring", Scheme = "0" };

The new object will have named properties:

if (jsonRequest.Data == "teststring") // returns true.

Upvotes: 1

Related Questions