问题
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.
回答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.
来源:https://stackoverflow.com/questions/34584169/send-and-receive-json-via-httpclient