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

age*_*tpx 16 asp.net jquery contextmenu

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"
 });
Run Code Online (Sandbox Code Playgroud)

我试图通过以下代码在ASHX文件中检索服务器端发布的JSON数据:

string strrequest = context.Request["OrderInfo"];
Run Code Online (Sandbox Code Playgroud)

但它总是返回null.我究竟做错了什么?

ron*_*dha 13

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


age*_*tpx 11

挖掘互联网.我发现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("<div><strong>" + fields[0] + "</strong></div>");
        //context.Response.Write("<div>" + fields[1] + "</div> ");  
    }

    string jsonRecord = s;
   }
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 11

来自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));
Run Code Online (Sandbox Code Playgroud)