[c#] How to let an ASMX file output JSON

I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.

However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:

[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
    public string[] UserDetails()
    {
        return new string[] { "abc", "def" };
    }
}

This question is related to c# json asmx

The answer is


Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.


A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).


To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse and change the WebMethod return type to void.

    [System.Web.Script.Services.ScriptService]
    public class WebServiceClass : System.Web.Services.WebService {
        [WebMethod]
        public void WebMethodName()
        {
            HttpContext.Current.Response.Write("{property: value}");
        }
    }

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).


Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.


To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse and change the WebMethod return type to void.

    [System.Web.Script.Services.ScriptService]
    public class WebServiceClass : System.Web.Services.WebService {
        [WebMethod]
        public void WebMethodName()
        {
            HttpContext.Current.Response.Write("{property: value}");
        }
    }

This is probably old news by now, but the magic seems to be:

  • [ScriptService] attribute on web service class
  • [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
  • Content-type: application/json in request

With those pieces in place, a GET request is successful.

For a HTTP POST

  • [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method

and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):

        $.ajax({
            url: "MyWebService.asmx/MethodName",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ searchString: q }),
            success: function (response) {                  
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ": " + jqXHR.responseText);
            }
        });

Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.


Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.


Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.


Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.


This is probably old news by now, but the magic seems to be:

  • [ScriptService] attribute on web service class
  • [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
  • Content-type: application/json in request

With those pieces in place, a GET request is successful.

For a HTTP POST

  • [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method

and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):

        $.ajax({
            url: "MyWebService.asmx/MethodName",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ searchString: q }),
            success: function (response) {                  
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ": " + jqXHR.responseText);
            }
        });

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).