44

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.

Majid
  • 13,853
  • 15
  • 77
  • 113
colin jobes
  • 441
  • 1
  • 5
  • 3

8 Answers8

61

I know 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();
cujo
  • 368
  • 3
  • 16
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • this is the most important 5 cents. I would like to add to it if you dont mind. – naveen Sep 18 '12 at 06:35
  • @Claudio Redi Please help me to resolve this... http://stackoverflow.com/questions/24732952/receive-the-jsonquery-string-in-webmethod?noredirect=1#comment38367134_24732952 – Sagotharan Jul 14 '14 at 09:53
  • This just adds the JSON to a string variable. How would you be able to parse the data in this string? What if this is an object that contains an array of objects? – Coded Container Jul 03 '17 at 15:44
  • @CodedContainer this question does not cover that... But you need to deserialize the string. See this https://stackoverflow.com/questions/10350982/deserialize-json-string-to-c-sharp-object – tno2007 Nov 08 '17 at 11:29
27

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;
           }
        }
    }
Andre
  • 1,852
  • 1
  • 16
  • 21
  • It did not work for me like this, but rather: `string myName = context.Request["firstName"]`; – Jaanus Aug 01 '13 at 14:33
  • @Jaanus Are you using POST? – Andre Sep 12 '13 at 11:59
  • @Andre can i able to get the { firstName: 'stack', lastName: 'overflow' } Full String. I need not to split. Please give a solution http://stackoverflow.com/questions/24732952/receive-the-jsonquery-string-in-webmethod?noredirect=1#comment38367134_24732952 – Sagotharan Jul 14 '14 at 09:51
4

If you send data to the server with respect of $.ajax the data will not be converted to JSON data automatically (see How do I build a JSON object to send to an AJAX WebService?). 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"] and context.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.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • 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 01 '10 at 11:13
  • To be able to see `file` parameter with `context.Request.QueryString["file"]` you should use `data` like `data: {file:'dave', type:'ward'}` (see my answer). Then query parameters with the names `file` and `type` will be defined and the data posted to server will be encoded like `file=dave?type=ward`. – Oleg Jun 01 '10 at 11:27
  • 2
    If your AJAX is POSTing, then the data will be in the Request.Form property, not QueryString. – Dave Thieben Sep 21 '10 at 17:01
  • @dave thieben: You are right. Thank you for the advice. I don't use ASHX myself. So instead of `Request.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 http://msdn.microsoft.com/en-us/library/system.web.httprequest.params.aspx) – Oleg Sep 21 '10 at 19:06
2
html
<input id="getReport" type="button" value="Save report" />

js
(function($) {
    $(document).ready(function() {
        $('#getReport').click(function(e) {
            e.preventDefault();
            window.location = 'pathtohandler/reporthandler.ashx?from={0}&to={1}'.f('01.01.0001', '30.30.3030');
        });
    });

    // string format, like C#
    String.prototype.format = String.prototype.f = function() {
        var str = this;
        for (var i = 0; i < arguments.length; i++) {
            var reg = new RegExp('\\{' + i + '\\}', 'gm');
            str = str.replace(reg, arguments[i]);
        }
        return str;
    };
})(jQuery);

c#
public class ReportHandler : IHttpHandler
{
    private const string ReportTemplateName = "report_template.xlsx";
    private const string ReportName = "report.xlsx";

    public void ProcessRequest(HttpContext context)
    {
        using (var slDocument = new SLDocument(string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~"), ReportTemplateName)))
        {
            context.Response.Clear();
            context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", ReportName));

            try
            {
                DateTime from;
                if (!DateTime.TryParse(context.Request.Params["from"], out from))
                    throw new Exception();

                DateTime to;
                if (!DateTime.TryParse(context.Request.Params["to"], out to))
                    throw new Exception();

                ReportService.FillReport(slDocument, from, to);

                slDocument.SaveAs(context.Response.OutputStream);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                context.Response.End();
            }
        }
    }

    public bool IsReusable { get { return false; } }
}
oyaebunterkrah
  • 101
  • 2
  • 6
1

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";
}
0

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" .

-1

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!

NotMe
  • 87,343
  • 27
  • 171
  • 245
-4

Try System.Web.Script.Serialization.JavaScriptSerializer

With casting to dictionary

AmirHd
  • 10,308
  • 11
  • 41
  • 60
Dewfy
  • 23,277
  • 13
  • 73
  • 121
  • 2
    Thanks for the reply. Could you elaborate a little please? What object should I be serializing? – colin jobes Jun 01 '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 01 '10 at 12:03