[英]Read and Parse JSON data from POST request in C#
I'm doing a POST request via JQuery's Ajax, with the type of data defined as json
, containing the values to be posted to server, something like Username: "Ali"
. 我正在通过JQuery的Ajax做一个POST请求,数据类型定义为json
,包含要发布到服务器的值,比如Username: "Ali"
。
What I need to do in a Handler, is to read the values, deserialize them to an object named User
. 我需要在Handler中做的是读取值,将它们反序列化为名为User
的对象。
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
User user = JsonConvert.DeserializeObject<User>(data);
While debugging, the value of data
is the following: 在调试时, data
的值如下:
Username=Ali&Age=2....
Now I'm sure this isn't JSON
, so the next line would certainly produce an error: 现在我确定这不是JSON
,所以下一行肯定会产生错误:
"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
What is the proper way to read JSON
data from POST request? 从POST请求中读取JSON
数据的正确方法是什么?
Client Side 客户端
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: {
Username: 'Ali',
Age: 2,
Email: 'test'
},
success: function (data) {
},
error: function (error) {
}
});
Convert your object to json string: 将您的对象转换为json字符串:
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: JSON.stringify({
Username: 'Ali',
Age: 2,
Email: 'test'
}),
success: function (data) {
},
error: function (error) {
}
});
I am not sure why your datastring is encoded like an url (as it seems). 我不确定为什么你的数据字符串被编码为url(看起来像)。
But this might solve the problem (altough i am not sure) 但这可能会解决问题(尽管我不确定)
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
String fixedData = HttpServerUtility.UrlDecode(data);
User user = JsonConvert.DeserializeObject<User>(fixedData);
Use This In c# file... Will give you result you require... 在C#文件中使用此...将为您提供所需的结果...
string username=Request.Form["Username"].ToString();
Similarly For others... I hope this will help you 同样对于其他人......我希望这会对你有所帮助
Another Answer Or you can send data like this 另一个答案或者您可以发送这样的数据
$.ajax({
url: '../Ajax/Ajax_MasterManagement_Girdle.aspx',
data: "Age=5&id=2"
type: 'POST',
success: function (data) {
}
});
ANd get the answer like this in c# 在c#中得到这样的答案
string Age=Request.Form["Age"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.