How to get JSON response from a 3.5 asmx web service
Asked Answered
E

4

14

I have the following method:

using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Collections;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]

// [System.Web.Script.Services.ScriptService]
public class Tripadvisor : System.Web.Services.WebService {

    public Tripadvisor () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }


    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HotelAvailability(string api)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string json = js.Serialize(api);
        //JsonConvert.SerializeObject(api);
        return json ;
    }

Here i set ResponseFormat attribute is json s still being returned as XML.

I want to json format using this asmx service Any ideas?

Eer answered 24/10, 2013 at 10:39 Comment(2)
Possible duplicate of Get JSON data with jQuery from a .NET service: confused with ajax setupTica
Possible duplicate of Asmx web service how to return JSON and not XML?Quadrireme
S
53

I faced the same issue, and included the below code to get it work.

[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write("Hello World");
    //return "Hello World";
}

Update:

To get a pure json format, you can use javascript serializer like below.

public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
    public void HelloWorld()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";           
        HelloWorldData data = new HelloWorldData();
        data.Message = "HelloWorld";
        Context.Response.Write(js.Serialize(data));


    }
}

public class HelloWorldData
{
   public String Message;
}

However this works for complex types, but string does not show any difference.

Stichous answered 24/10, 2013 at 10:57 Comment(5)
did you try removing the return and use response.write() instead??Stichous
Okey now it give me json but not pure for example i pass parameter like ABC and it return "ABC" but pure json is like {"ABC"}Eer
:thanks dear i got solution but i am quite confused if i am making class than it ll give json responce otherwise not....why? can you plz elaborate itEer
Thank you it helped me to easily convert my list<class> object in xml to json object . Thank youMercurochrome
While this answer may appear to give you correct result, it defies the very purpose of web services and removes its ability to return either json or xml in different situations. Please do not use it and refer to a proper solution instead.Tica
Q
4

Dear future readers: The currently accepted answer is not the right way. It ties you to using the JavaScriptSerializer and you lose the ability to request xml (or indeed any serialization format which may come along in the future). The "right way" also involves less code!

If you decorate your service class with the [ScriptService] attribute - which you have - then ASP.NET 3.5+ should automatically serialise the response to JSON provided your Ajax call requests JSON. The suggestions to serialise to JSON manually are simply wrong, unless you wish to use a different serialiser such as Newtonsoft.

That you were seeing XML suggests one of the following:

  • You are not requesting JSON in your Ajax call - please see working example code below
  • Possibly some web.config entries are missing, according to an answer here (disclaimer: I don't have most of these in a production web.config; only start playing with these if nothing else works)

Here is a simple working example of a JSON enabled ASMX web service:

<%@ WebService Language="C#" Class="WebService" %>
using System;
using System.Collections.Generic;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    [WebMethod]
    public MyClass Example()
    {
        return new MyClass();
    }

    public class MyClass
    {
        public string Message { get { return "Hi"; } }
        public int Number { get { return 123; } }
        public List<string> List { get { return new List<string> { "Item1", "Item2", "Item3" }; } }
    }
}

JavaScript to request it and process the response (we'll simply pop up a JS alert with the message from MyClass.Message) :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.js" type="text/javascript"></script>  
</head>
<body>
    <script type="text/javascript">
        $.ajax({
            type: "POST",
            url: "WebService.asmx/Example",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ }",
            error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
            success: function (msg) {
                alert(msg.d.Message);
            }
        });
    </script>
</body>
</html>

Http request:

POST http://HOST.com/WebService.asmx/Example HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://HOST.com/Test.aspx
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 3
Host: HOST.com

{ }

HTTP response:

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 20 Feb 2018 08:36:12 GMT
Content-Length: 98

{"d":{"__type":"WebService+MyClass","Message":"Hi","Number":123,"List":["Item1","Item2","Item3"]}}

Result:

"Hi" is displayed in a JS popup.

Quadrireme answered 21/2, 2018 at 11:56 Comment(5)
Which header of the Http Request is the one that makes it work for JSON? "Accept"? "Content-Type"? Both?Kestrel
@Kestrel Logically it should be "Accept" or both.... The Accept header in the request tells the server the content types that the client is expecting in the response body. The Content-Type header in the request tells the server what type of content is in the request body. In practice: Try it with Fiddler or a similar tool.Quadrireme
I am using SoapUI to test this method. I added "Accept: application/json" as a new header (I did not add "Content-Type: application/json;charset=UTF-8" because SoapUI is sending XML) but I keep getting XML as a response. I also checked the web.config and added some missing entries to no avail. I can see the "Accept" request header is sent but the reponse header has "Content-Type: text/xml; charset=utf-8" not "applicacion/json".Kestrel
How come your WebService+MyClass JSON response wrapped in another object? Where does this other object with the d property come from?Ascertain
@Ascertain The .d property is a Microsoft thing - see, for example, Why do I need to use .d to access data returned by jQuery AJAX?Quadrireme
B
1

Just a doubt. When are you not getting a JSON response? Because when you invoke the web service from the client (I am assuming a web browser, i.e. xhr), you should specify the content type header on the request as "application/json; charset=yourcharset".

I believe the above solution always returns json, no matter what the content type is specified from the client. The dotnet asmx framework allows this using the content-type header method, so the above could be classified as a hack, when a neat solution is available.

Similar question at Return Json Data from ASMX web service

This might help too -> http://forums.asp.net/p/1054378/2338982.aspx#2338982

P.S: I am assuming you are using dotnet version 4.

Bruch answered 18/12, 2013 at 11:52 Comment(0)
D
0

Sometimes we don't have access to make changes in WebService definition and sometimes we should not make changes in WebServices! so the best solution is set contentType="application/json; charset=..." in your request. just this!

For example you can use below code (if you are using jquery) instead of changing somethings in WebService:

$.ajax({
        type: "POST",
        url: '/ServiceName.asmx/WebMethodName',
        date: {},
        contentType: "application/json; charset=utf-8",
        success: function (data) {                
                // Some code;

        }
    });

Then you can use JSON.parse(data.d) to access json structure of your data.

Dematerialize answered 13/10, 2020 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.