JEREEF February 2016

A circular reference was detected while serializing an object of type 'System.Web.HttpContext'

I want to return a json object from an asp.net web service in this format {"Part_ID":"2","Part_NAME":"\u0645\u0633\u062a\u0644\u0632\u0645\u0627 "}

but I get the following error

System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Web.HttpContext'.

Code is :

      public class Service : System.Web.Services.WebService
      {
        public string name;  
        public Service()
        {

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

        [WebMethod(Description = "Your Description")]
        public string FunctionName()
        {
          var a = new Service { name = "tamzinho" };
          JavaScriptSerializer js = new JavaScriptSerializer();
          string retJSON = js.Serialize(a);
          return retJSON;
        }
      }

Answers


Nathan February 2016

var a = new Service { name = "tamzinho" };
...
string retJSON = js.Serialize(a);

This code is your problem: the serialization will be attempted infinitely because you then try to serialize an instance of the same class, which will attempt to serialize another instance (and so on...)

Separate your data into a separate object.

eg:

public class MyServiceData {
   public string Name { get; set; }
   public string Description { get; set; }
}

public class Service : System.Web.Services.WebService
{
   public MyServiceData GetInfo(int partId) {
       ... data access code
       var result = new MyServiceData() { 
           Name = ...;
           Description = ...;
       };

      ... serialize result data to javascript
      return result;
   }
}

Post Status

Asked in February 2016
Viewed 2,394 times
Voted 6
Answered 1 times

Search




Leave an answer