简体   繁体   English

使用主体中的JObject调用Web Api

[英]Making a call to a Web Api with a JObject in the body

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: 我想在后面的代码中调用已构建的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)
        );

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? 因此,有人将如何构造对Web api(在C#中)的http调用,并将上述JObject张贴在消息正文中? I wouldn't necessarily need anything returned, except maybe a generic success or failure message. 我可能不需要返回任何东西,除了一般的成功或失败消息。 I appreciate any help given. 我感谢您提供的任何帮助。

Here's an example using System.Net.HttpClient 这是使用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);
 }

I ended up changing the json into a .net object and got my problem solved. 我最终将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
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM