通过HttpClient发送和接收json [英] Send and receive json via HttpClient

查看:130
本文介绍了通过HttpClient发送和接收json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm designing 2 websites and wanna send a json from the first website to the second:

// 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 控制器的

Action Info :

Action Info of the Contacts controller in the second website:

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

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

Can you tell me how to get the json?

p/s:很抱歉,请给我提供代码问题,我一直在Google搜索中寻找问题,但未发现任何示例.我想在服务器端执行此操作,而不是在客户端使用ajax.

p/s: Sorry for give me the code question, I'd been looking for on Google search but no sample was found in my case. I wanna do this in server side instead of using ajax in client side.

推荐答案

您需要告诉客户端您要发送的内容.在这种情况下,这是JSON字符串有效负载

You need to tell the client what you want to send. In this case it's a JSON string payload

var content = new StringContent(json, Encoding.UTF8, "application/json");

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

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

As for the second website you have a few ways to receive it. But here is a quick and dirty way if you're just sending the JSON as you showed in form first site

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

这是您如何执行此操作的快速示例.您应该检查以确保您要查找的密钥确实在有效载荷中.

This is a quick sample of how you can do it. You should check to make sure that the keys you are looking for are actually in the payload.

您也可以这样

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;
   }
}

该框架应该能够通过绑定来重建对象.

The framework should be able to reconstruct the object through binding.

这篇关于通过HttpClient发送和接收json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆