1

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", ???);
   }
}

Action Info of the Contacts controller in the second website:

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

Can you tell me how to get the json?

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.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Tân
  • 1
  • 15
  • 56
  • 102

1 Answers1

1

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

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.

You can also do it this way

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.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • A small question: Why do you send a string and receive the string by `IDictionary`? Implicit conversion `string` to `IDictionary`? – Tân Jan 04 '16 at 03:39
  • You converted a `Dictionary` package to json `string` to send it to the other site. The string is just how you send it over. When it reaches its destination the frame work is smart enough to know how to convert it to other types. `Dictionary` inherits from `IDictionary`. You could just as easily used `Dictionary` – Nkosi Jan 04 '16 at 03:44
  • The json string is just a representation of the object/data you want to send. – Nkosi Jan 04 '16 at 03:48