0
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public ServiceResponse abc()
{
    ServiceResponse sr = new ServiceResponse();
    return sr;
}

but when I hit http://localhost:xxxx/WebService.asmx/abc in browser I get back xml

<ServiceResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<success>false</success>
<message>Error</message>
</ServiceResponse>

But I want it to produce json (which i can do from mvc controller easily, but i am bound to use asmx)

What could i do to produce json frommy webservice.asmx ?

I picked up a working function from my mvc and added to service and decorated it like

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public object bcd()
{
    return new { message = "Success", success = true; data : {} };
}

It gives following error

System.InvalidOperationException: There was an error generating the
XML document. ---> System.
InvalidOperationException: &lt;&gt;f__AnonymousType5`1[System.Int32] cannot be serialized
because it does not have a parameterless constructor.

So I use this class for returning response, this is object type to which i want to get as json

public class ServiceResponse
{
    public ServiceResponse()
    {
        success = false;
        message = "Error";
    }
    public ServiceResponse(string mesg)
    {
        success = false;
        message = mesg;
    }   

    public bool success { get; set; }
    public object data { get; set; }
    public string message { get; set; }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sami
  • 8,168
  • 9
  • 66
  • 99
  • what happens if you use fiddler and create a request with an header `content-type: application/json` – rene Sep 12 '15 at 15:18
  • You'll need to upgrade from the deprecated `.asmx` webservice technology to **WCF** (or the ASP.NET Web API) to get JSON. – marc_s Sep 12 '15 at 15:20

0 Answers0