且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过HttpClient发送和接收json

更新时间:2023-01-17 09:10:33

您需要告诉客户端您要发送的内容.在这种情况下,这是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.