Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let an ASMX file output JSON

Tags:

json

c#

asmx

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" };     } } 
like image 542
doekman Avatar asked Oct 17 '08 07:10

doekman


1 Answers

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}");         }     } 
like image 85
iCorrect Avatar answered Sep 30 '22 23:09

iCorrect