How to return a JSON object in standard web forms .Net

I would suggest an HttpHandler. No page lifecycle (so it is blazing fast) and much cleaner code-separation, as well as reusability.

Add a new item to your project of type “Generic Handler”. This will create a new .ashx file. The main method of any class that implements IHttpHandler is ProcessRequest. So to use the code from your original question:

public void ProcessRequest (HttpContext context) {

    if(String.IsNullOrEmpty(context.Request["day"]))
    {
        context.Response.End(); 
    }

    string json = "";
    byte[] bytes = getByteArray();

    json = JsonConvert.SerializeObject(bytes);
    context.Response.ContentType = "text/json";
    context.Response.Write(json);
}

Change the url in your AJAX call and that should do it. The JavaScript would look like this , where GetFileHandler.ashx is the name of the IHttpHandler you just created:

$.ajax(
    {
        type: "POST",
        async: true,
        url: 'Handlers/GetFileHandler.ashx',
        data: "Day=" + $.toJSON(day),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            console.log("SUCCESS:" + msg);
        },
        error: function (msg) {
            console.log("error:" + msg);
        }
    });

Another small point to consider, if you need access to the Session object from within the Handler code itself, make sure to inherit from the IRequiresSessionState interface:

public class GetFileHandler : IHttpHandler, IRequiresSessionState

Leave a Comment