Tuesday, 11 October 2011

ASMX web service is not returning JSON data in IIS7

This code was perfectly working and returning json data when was being called from Jquery in IIS 5-6.However when it was deployed to IIS7, it was constantly returning xml response.


[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 public class SomeService : System.Web.Services.WebService
 { public SomeService()
 { //Uncomment the following line if using 
designed components //InitializeComponent(); }
 [WebMethod] [System.Web.Script.Services.ScriptMethod
(ResponseFormat = ResponseFormat.Json)] 
public List<sometype> getlist2() 
{ List<sometype> localtaglist =
 new List<sometype>(); ... foreach (...) 
{ sometype localtag = new sometype(); ... localtaglist.Add(localtag); } 
return localtaglist

Add following lines of code to the web method and it will successfully 
return data in json format.

Context.Response.ContentType = "application/json"; 

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
 Context.Response.ContentType = "application/json"
Context.Response.Write( jsonSerializer.Serialize(localtaglist));