Tuesday, March 19, 2013

ASP.NET - Passing JSON from jQuery to ASHX



I'm trying to pass JSON from jQuery to a .ASHX file. Example of the jQuery below:
$.ajax({
      type: "POST",
      url: "/test.ashx",
      data: "{'file':'dave', 'type':'ward'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",      
    });
How do I retrieve the JSON data in my .ASHX file? I have the method:
public void ProcessRequest(HttpContext context)
but I can't find the JSON values in the request.
Thanks in advance.
share|improve this question

7 Answers

I kknow this is too old, but just for the record I'd like to add my 5 cents
You can read the json object on the server with this
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
share|improve this answer
This is the proper way to get it to work. Perfect. – ruionwriting Mar 25 '12 at 0:28
this is the most important 5 cents. I would like to add to it if you dont mind. – naveen Sep 18 '12 at 6:35
The following solution worked for me:
Client Side:
        $.ajax({
            type: "POST",
            url: "handler.ashx",
            data: { firstName: 'stack', lastName: 'overflow' },
            // DO NOT SET CONTENT TYPE to json
            // contentType: "application/json; charset=utf-8", 
            // DataType needs to stay, otherwise the response object
            // will be treated as a single string
            dataType: "json",
            success: function (response) {
                alert(response.d);
            }
        });
Server Side .ashx
    using System;
    using System.Web;
    using Newtonsoft.Json;

    public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string myName = context.Request.Form["firstName"];

            // simulate Microsoft XSS protection
            var wrapper = new { d = myName };
            context.Response.Write(JsonConvert.SerializeObject(wrapper));
        }

        public bool IsReusable
        {
           get
           {
                return false;
           }
        }
    }
share|improve this answer
If you send data to the server with respect of $.ajax the data will not be converted to JSON data automatically (see http://stackoverflow.com/questions/2737525/how-do-i-build-a-json-object-to-send-to-an-ajax-webservice/2738086#2738086). So you can use contentType: "application/json; charset=utf-8" and dataType: "json" and stay don't convert data with JSON.stringify or$.toJSON. Instead of
data: "{'file':'dave', 'type':'ward'}"
(manual converting of data to JSON) you can try use
data: {file:'dave', type:'ward'}
and get the data on the server side with context.Request.QueryString["file"] andcontext.Request.QueryString["type"] constructs. If you do receive some problems with this way then you could try with
data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}
and usage DataContractJsonSerializer on the server side.
share|improve this answer
Thanks for the reply. The issue I'm having is just that I can't get the JSON data into the request object when using an ASHX page. The value of context.Request.QueryString["file"] is always null. Would you know how to get the JSON data into the request? – colin jobes Jun 1 '10 at 11:13
To be able to see file parameter with context.Request.QueryString["file"] you should use datalike data: {file:'dave', type:'ward'} (see my answer). Then query parameters with the namesfile and type will be defined and the data posted to server will be encoded like file=dave?type=ward. – Oleg Jun 1 '10 at 11:27
2 
If your AJAX is POSTing, then the data will be in the Request.Form property, not QueryString. – dave thiebenSep 21 '10 at 17:01
@dave thieben: You are right. Thank you for the advice. I don't use ASHX myself. So instead ofRequest.QueryString the Request.Form would be better. It seems to me that Request.Params is the best way because it will work for both GET and POST (see msdn.microsoft.com/en-us/library/…) – Oleg Sep 21 '10 at 19:06
you have to defined the handler properties in web configuration file to handle the user defined extension request formats. here the user defined extension is ".api"
add verb="*" path="test.api" type="test" replace the url: "/test.ashx" to url: "/test.api" .
share|improve this answer
Try System.Web.Script.Serialization.JavaScriptSerializer - with casting to dictionary
share|improve this answer
1 
Thanks for the reply. Could you elaborate a little please? What object should I be serializing? – colin jobesJun 1 '10 at 10:04
@colin, I'm preferring Dictionary, but you can persist any object, for example in your sample: class MyObj{ public String file, type; } – Dewfy Jun 1 '10 at 12:03
if using $.ajax and using .ashx to get querystring ,dont set datatype
$.ajax({ 
    type: "POST", 
    url: "/test.ashx", 
    data: {'file':'dave', 'type':'ward'}, 
    **//contentType: "application/json; charset=utf-8",   
    //dataType: "json"**    
}); 
i get it work!
share|improve this answer
This works for calling web services. Not sure about .ASHX
$.ajax({ 
    type: "POST", 
    url: "/test.asmx/SomeWebMethodName", 
    data: {'file':'dave', 'type':'ward'}, 
    contentType: "application/json; charset=utf-8",   
    dataType: "json",
    success: function(msg) {
      $('#Status').html(msg.d);
    },
    error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert('Error: ' + err.Message);
    }
}); 



[WebMethod]
public string SomeWebMethodName(string file, string type)
{
    // do something
    return "some status message";
}
share|improve this answer

No comments:

Post a Comment