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" };
}
}
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).
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.
This is probably old news by now, but the magic seems to be:
With those pieces in place, a GET request is successful.
For a HTTP POST
and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):
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 theWebMethod
return type tovoid
.From WebService returns XML even when ResponseFormat set to JSON: