我将一个json对象发布到带有C#代码的ASP.Net MVC控制器。为了简化这个示例,对象只是一个具有make和model属性的汽车。一切都适用于下面的代码。我的问题是 - 如何发布多个参数?例如,我如何发布JSON对象,电子邮件地址和电话号码?
//post to form
string requestData = "{\"Make\":\"Ford\",\"Model\":\"Mustang\"}";
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://receiving.url/showdata");
request.Method = "POST";
request.ContentType = "application/json";
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.Write(result);
这是从代码中检索json对象的Controller代码,然后输出json以进行验证。
[HttpPost]
public JsonResult showdata(Car c)
{
return Json(c, JsonRequestBehavior.AllowGet);
}
我希望做这样的事情:
[HttpPost]
public JsonResult showdata(Car c, string email, string phone)
{
return Json(c, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:9)
像这样:
string requestData = "{\"c\": {\"Make\":\"Ford\",\"Model\":\"Mustang\"}, \"email\": \"foo@bar.com\", \"phone\": \"1111\"}";
甚至更好地使用JavascriptSerializer:
using System;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
class Program
{
static void Main()
{
var serializer = new JavaScriptSerializer();
string requestData = serializer.Serialize(new
{
c = new
{
make = "Ford",
model = "Mustang"
},
email = "foo@bar.com",
phone = "1111"
});
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var result = client.UploadData("http://receiving.url/showdata", Encoding.UTF8.GetBytes(requestData));
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
}
将正确处理JSON序列化对象,就像使用这些字符串连接一样,如果数据包含一些特殊字符,您的请求可能会轻易破坏。
哦,在我忘记之前:使用视图模型。
所以而不是:
[HttpPost]
public JsonResult showdata(Car c, string email, string phone)
{
...
}
你应该肯定有:
[HttpPost]
public ActionResult ShowData(ShowDataViewModel data)
{
...
}
然后:
string requestData = serializer.Serialize(new
{
make = "Ford",
model = "Mustang",
email = "foo@bar.com",
phone = "1111"
});
还有一句话:当您使用JsonRequestBehavior.AllowGet
修饰控制器操作时,返回JSON时不需要[HttpPost]
,因此永远不能使用GET动词调用此操作。
答案 1 :(得分:1)
这不是问题,请你提出要求:
"{\"Make\":\"Ford\",\"Model\":\"Mustang\", \"email\":\"xxx\", \"phone\":\"yyy\" }";
ASP.NET MVC Json binder应该是聪明的,应该正确地为方法,例如:
public JsonResult showdata(Car c, string email, string phone)