Edi
Edi

Reputation: 989

Asp.net WebService function doesn't return JSON

I've read every post about this issue, but nothing solved the problem. I'll be glad if someone can help me with that.

There's an MVC3 project with a web service that I added. I have only one function called Test, and when I call it through an HTTP GET method (regular url) , it returns the data with XML format instead of JSON. How can I make it return JSON?

The web service:

namespace TestServer
{
    [WebService]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class TestWebservice : System.Web.Services.WebService
    {  
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        public List<string> Test()
        {    
            return new List<string>
                {
                    {"Test1"},
                    {"Test2"}
                };                    
        }
    }
}

The web.config (only relevant parts):

<configuration>
  <location path="TestWebservice.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
        </protocols>
      </webServices>
    </system.web>
  </location>  
  <system.web>
    <webServices>
      <protocols>
        <clear/>
      </protocols>
    </webServices>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx"
        type="System.Web.Script.Services.ScriptHandlerFactory"
        validate="false"/>
    </httpHandlers>
  </system.web>
</configuration>


The url:

http://localhost:49740/testwebservice.asmx/Test


The result (which is not what I want):

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
  <string>Test1</string>
  <string>Test2</string>
</ArrayOfString>


I'll be glad if someone can help me.

Upvotes: 1

Views: 2288

Answers (2)

VJAI
VJAI

Reputation: 32758

The REST service serialize the data in particular format(XML, JSON) based upon the Accept header send from the client. It is the Accept header that says to the service which formats the client can accept.

When you trying to access the service directly from the browser URL the value of the Accept header is set to some default value as below (in firefox)

text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

The above header explicitly says that I can accept html, xhtml or xml. Since the application/xml format is explicitly specified but not application/json the REST service returns the data in xml format. (I don't understand what is the use of ResponseFormat = ResponseFormat.Json though).

So if you want to make the service return JSON data you have to specify the accept header the corresponding format. If you are using jQuery you can utilize the $.getJSON() that will set the accept header as "application/json" or you can even use $.ajax with dataType as json.

http://prideparrot.com/blog/archive/2011/9/returning_json_from_wcfwebapi

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You need to specify the content type HTTP header to application/json when sending the request. For example if you are using jQuery AJAX you could do the following:

$.ajax({
    url: '/testwebservice.asmx/Test',
    type: 'GET',
    contentType: 'application/json',
    success: function(result) {
        alert(result.d[0]);
    }
});

Also you need to enable the GET verb on your [ScriptMethod] attribute:

[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[WebMethod]
public List<string> Test()
{
    return new List<string>
    {
        {"Test1"},
        {"Test2"}
    };
}

You could also get rid of everything you put in your web.config about this service. It's not necessary.

Oh and by the way, classic ASMX web services is an obsolete technology. You should use more recent technologies such as ASP.NET MVC controller actions returning JSON, WCF, or even the bleeding edge ASP.NET MVC 4 Web API.

Upvotes: 3

Related Questions