Chris G. Williams
Chris G. Williams

Reputation: 282

Passing a custom object to a REST endpoint with C#

I have a rest endpoint that accepts a single custom object parameter containing two properties.

Let's call the param InfoParam

public class InfoParam
{
    public long LongVar { get; set; }
    public string StringVar { get; set; }
}

My code I have is as follows:

infoParam.LongVar = 12345678;
infoParam.StringVar = "abc"

var myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";

var content = string.Empty;

using (var theResponse = (HttpWebResponse)MyRequest.GetResponse())
{
    using (var stream = theResponse.GetResponseStream())
    {
        using (var sr = new StreamReader(stream))
        {
            content = sr.ReadToEnd();
        }
    }
}

So I have the InfoParam variable, with the two values, but I can't figure out where to pass it in to the REST endpoint.

Upvotes: 0

Views: 1893

Answers (2)

tmaj
tmaj

Reputation: 35105

You have to write it int the `Content (and set content-type). Check out How to: Send data by using the WebRequest class

The recommendation is to use System.Net.Http.HttpClient instead.

Please note that you should know what content the server expects ('application/x-www-form-urlencoded`, json, etc.)

The following snippet is from POST JSON data over HTTP

// Construct the HttpClient and Uri. This endpoint is for test purposes only.
        HttpClient httpClient = new HttpClient();
        Uri uri = new Uri("https://www.contoso.com/post");

        // Construct the JSON to post.
        HttpStringContent content = new HttpStringContent(
            "{ \"firstName\": \"Eliot\" }",
            UnicodeEncoding.Utf8,
            "application/json");

        // Post the JSON and wait for a response.
        HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
            uri,
            content);

        // Make sure the post succeeded, and write out the response.
        httpResponseMessage.EnsureSuccessStatusCode();
        var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
        Debug.WriteLine(httpResponseBody);

In your case the content would be something like this

HttpStringContent content = new HttpStringContent(
            JsonConvert.SerializeObject(infoParam), // using Json.Net;
            UnicodeEncoding.Utf8,
            "application/json");

Upvotes: 0

Sam Axe
Sam Axe

Reputation: 33738

You need to turn the object into a stream of bytes that can be added to the Request stream - which will in turn be sent as the HTTP POST body. The format of these bytes needs to match what the server expects. REST endpoints usually expect these bytes to resemble JSON.

// assuming you have added Newtonsoft.JSON package and added the correct using statements
using (StreamWriter writer = new StreamWriter(myRequest.GetRequestStream()) {
    string json = JsonConvert.SerializeObject(infoParam);
    writer.WriteLine(json);
    writer.Flush();
}

You'll probably want to set various other request parameters, like the Content-Type header.

Upvotes: 1

Related Questions