4

I want to, in code behind, call a Web Api I've built and save some data that I have stored in the following JObject:

var json = new JObject(
            new JProperty("firstName", txtFirstName.Text),
            new JProperty("lastName", txtLastName.Text),
            new JProperty("companyName", txtCompanyName.Text),
            new JProperty("email", txtEmail.Text),
            new JProperty("phone", txtPhone.Text)
        );

Problem is, I'm not sure the best way to go about this. I've found a plethora of examples that are close to the answer, but not quite what I'm looking for. So, how would someone construct an http call to a web api(in C#) and have the aforementioned JObject be posted in the body of the message? I wouldn't necessarily need anything returned, except maybe a generic success or failure message. I appreciate any help given.

Tim
  • 41,901
  • 18
  • 127
  • 145
Rex_C
  • 2,436
  • 7
  • 32
  • 54

2 Answers2

3

Here's an example using System.Net.HttpClient

 string jsonText = json.ToString();
 using (var client = new HttpClient())
 {
      var httpContent = new StringContent(jsonString);
      httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

      HttpResponseMessage message = await client.PostAsync("http://myWebUrl/send", httpContent);
 }
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
0

I ended up changing the json into a .net object and got my problem solved.

using System.Net.Http;
using System.Net.Http.Headers;

        var userData = new User()
        {
            firstName = txtFirstName.Text,
            lastName = txtLastName.Text,
            companyName = txtCompanyName.Text,
            email = txtEmail.Text,
            phone = txtPhone.Text
        };
            client.BaseAddress = new Uri("http://yourBaseUrlHere");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("requestUrlHere", user);
            if (response.IsSuccessStatusCode)
            {
                //Success code
            }
Rex_C
  • 2,436
  • 7
  • 32
  • 54