如何通过ASP.Net context.Request检索JSON

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。 我究竟做错了什么?

  1. 从HttpContext.Current.Request.InputStream获取请求体。
  2. 读取输入流并转换为字符串
  3. 使用javascriptserializer将json对象反序列化为强类型对象(确保json属性与强类型计数器部分共享同一名称)

挖掘互联网。 我发现IE完全接收POST请求有问题。 @ ronaldwidha对InputStream的建议与我发现的类似。 但不是使用javascriptserializer我使用JSON.NET代码片段在下面,我希望这将有助于其他类似的问题

  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("
" + fields[0] + "
"); //context.Response.Write("
" + fields[1] + "
"); } string jsonRecord = s; } }

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

Request []只会查看form params和quetystring。 您需要做一个表格post或使用qs或自己解析请求正文。

我想你可以从HttpCurrent.Context.Request.GetResponse()获取请求体。

首先validation内容类型标头可能是个好主意。