在正文中使用JObject调用Web Api

时间:2014-05-06 22:31:02

标签: c#

我想在代码背后调用Web Api我已经构建并保存了一些我存储在以下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)
        );

问题是,我不确定最好的方法。我找到了许多接近答案的例子,但并不是我所寻找的。那么,如何构建对Web api的http调用(在C#中)并将上述JObject发布在消息正文中?除了通用的成功或失败消息之外,我不一定需要返回任何内容。我感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

以下是使用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);
 }

答案 1 :(得分:0)

我最终将json更改为.net对象并解决了我的问题。

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
            }