var OrderInfo = {"ProductID":
"ProductIDValue",
"ProductName": "ProductName",
"Quantity": 1,
"Amount": 9999,
"SLQuantity": 9999,
"SLDate": "08/03/2010"
};
var DTO = { 'OrderInfo': OrderInfo };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JasonHandler.ashx",
data: JSON.stringify(DTO),
dataType: "json"
});
我正在尝试通过以下代码在ASHX文件中检索服务器端发布的JSON数据:
string strrequest = context.Request["OrderInfo"];
但它总是返回null。我做错了什么?
答案 0 :(得分:13)
答案 1 :(得分:11)
挖掘互联网。我发现IE完全接收POST请求有问题。 @ ronaldwidha对InputStream的建议与我发现的相似。但是,我使用JSON.NET代码片段而不是使用javascriptserializer,我希望这可以帮助其他类似的问题
public class JasonHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
System.IO.Stream body = context.Request.InputStream;
System.Text.Encoding encoding = context.Request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (context.Request.ContentType != null)
{
context.Response.Write("Client data content type " + context.Request.ContentType);
}
string s = reader.ReadToEnd();
string[] content = s.Split('&');
for (int i = 0; i < content.Length; i++)
{
string[] fields = content[i].Split('=');
//context.Response.Write("<div><strong>" + fields[0] + "</strong></div>");
//context.Response.Write("<div>" + fields[1] + "</div> ");
}
string jsonRecord = s;
}
}
答案 2 :(得分:10)
来自http://dailydotnettips.com/2013/09/26/sending-raw-json-request-to-asp-net-from-jquery/
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));
答案 3 :(得分:-1)
Request []只会查看form params和quetystring。您需要做一个表格帖子或使用qs或自己解析请求正文。
答案 4 :(得分:-2)
我认为你可以从HttpCurrent.Context.Request.GetResponse()获取请求体。
首先验证内容类型标题可能是个好主意。