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.
You need to specify the content type HTTP header to
application/jsonwhen sending the request. For example if you are using jQuery AJAX you could do the following:Also you need to enable the GET verb on your
[ScriptMethod]attribute:You could also get rid of everything you put in your
web.configabout 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.