How to retrieve JSON via ASP.Net context.Request

agentpx picture agentpx · Aug 3, 2010 · Viewed 40.1k times · Source
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"
 });

I'm trying to retrieve posted JSON data on server side in an ASHX file via this code:

string strrequest = context.Request["OrderInfo"];

but it always return null. What Am I doing wrong?

Answer

ronaldwidha picture ronaldwidha · Aug 3, 2010
  1. get the request body from HttpContext.Current.Request.InputStream.
  2. read the input stream and convert to string
  3. use javascriptserializer to deserialize the json object to a strongly type object (ensure the json properties share the same name as the strongly type counter part)