I have an ASP.NET web application.
It has a web service, with several web methods.
All of these web methods are based on the default settings. For instance:
using System.Web.Services;
namespace WebApplication2
{
[WebService(Namespace = "http://mydomain.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public Person GetPersonById(int id)
{
Person result = new Person();
// code...
return person;
}
}
}
The response is in SOAP (XML) format.
My question: Can I change the response’s format to JSON, based on an input parameter or on a header?
The response type of a ASMX Web Service is specified by the ResponseFormat attribute on the individual web method.
E.g:
or
So AFAIK the answer is no – you cannot return both (from one method that is).
I’m sure there are some hacks you can do, but this is the recommended way.
If you want to start returning both types, you should move to a more RESTful approach, either with WCF REST, OData or ASP.NET MVC.
In those technologies, the callee can specify the response type they wish:
Note how both calls are one physical resource.
On a side note, your JSON web service calls should be HTTP POST, for security reasons mentions by "The Goo" here.