Search code examples
c#asp.netjsonweb-servicesasmx

{"d": null} showing after JSON response from ASMX Web Service


I've been searching and read and tried many different variations to make sure the pesky {"d": null} isn't appended to the end of my JSON response, however, I'm at a loss. I have an .asmx web service that does uses the Context.Response.Write method like so:

DataTable products = my_source;

string jsonResponse = JsonConvert.SerializeObject(products);//, Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore} );

this.Context.Response.Clear();
this.Context.Response.ContentType = "application/json; charset=utf-8";

this.Context.Response.Write(jsonResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();

I've tried to also use Flush() after the write with no success. That would only return the JSON but also an error saying cannot flush after headers have been sent. I've used Write.End() instead of CompleteRequest and that would also truncate the ] from the JSON response. Rather than using the Context.Response.Write, I would return a string, however, this too, leaves off the ] bracket at the end of the JSON response.

My method attributes are as follows:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

I'm invoking the service with a simply ajax request:

$.ajax({
    url : '/ProductCatalog/ProductMasterWS.asmx/GetProducts',
    type : 'GET',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {
        populate(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(xhr.status + " " + thrownError.stack);
    }
});

Any ideas/advice is greatly appreciated!


Solution

  • Don't implement your web service like that, just return a POCO object containing your response from the web method. ASMX takes care of the rest for you.