【问题标题】:Send and receive json via HttpClient通过 HttpClient 发送和接收 json
【发布时间】:2016-01-04 03:05:09
【问题描述】:

我正在设计 2 个网站,并希望将 json 从第一个网站发送到第二个网站:

// Action from the first website
public async Task<ActionResult> Index()
{
   using (var client = new HttpClient())
   {
      var package = new Dictionary<string, string>()
      {
         { "Name", "Julie" }
         { "Address", "UK" }
      };

      string json = JsonConvert.SerializeObject(package);

      var response = await client.PostAsync("thesecondsite.com/contacts/info", ???);
   }
}

第二个网站Contacts控制器的动作Info

[HttpPost]
public ActionResult Info()
{
   // How can I catch the json here?
   // string json = ...
}

你能告诉我如何获取json吗?

p/s:对于give me the code 的问题,我很抱歉,我一直在 Google 搜索中寻找,但在我的案例中没有找到样本。我想在服务器端执行此操作,而不是在客户端使用 ajax。

【问题讨论】:

    标签: c# json asp.net-mvc dotnet-httpclient


    【解决方案1】:

    您需要告诉客户您要发送什么。在这种情况下,它是一个 JSON 字符串有效负载

    var content = new StringContent(json, Encoding.UTF8, "application/json");
    
    var response = await client.PostAsync("thesecondsite.com/contacts/info", content);
    

    至于第二个网站,您有几种接收方式。但是,如果您只是按照表单第一个站点中显示的方式发送 JSON,那么这是一种快速而肮脏的方式

    [HttpPost]
    public ActionResult Info(IDictionary<string,string> payload) {
       if(payload!=null) {
           var Name = payload["Name"];
           var Addredd = payload["Address"];
       }
    }
    

    这是您如何做到这一点的快速示例。您应该检查以确保您要查找的密钥确实在有效负载中。

    你也可以这样做

    class Contact {
        public string Name{get;set;}
        public string Address {get;set;}
    }
    ...
    
    [HttpPost]
    public ActionResult Info(Contact payload) {
       if(contact!=null){
           var Name = contact.Name;
           var Address = contact.Address;
       }
    }
    

    框架应该能够通过绑定重构对象。

    【讨论】:

    • 一个小问题:为什么发送一个字符串,然后通过IDictionary&lt;string, string&gt;接收字符串?隐式转换 stringIDictionary&lt;string, string&gt;?
    • 您将 Dictionary&lt;string, string&gt; 包转换为 json string 以将其发送到其他站点。字符串就是您发送它的方式。当它到达目的地时,框架足够聪明,知道如何将其转换为其他类型。 Dictionary&lt;string, string&gt; 继承自 IDictionary&lt;string, string&gt;。你可以很容易地使用Dictionary&lt;string, string&gt;
    • json 字符串只是您要发送的对象/数据的表示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2012-07-28
    相关资源
    最近更新 更多