Search code examples
postwebrequestwebresponsecustom-object

How to post a custom user defined object to a url?


MyObject myobject= new MyObject(); myobject.name="Test"; myobject.address="test"; myobject.contactno=1234; string url = "http://www.myurl.com/Key/1234?" + myobject; WebRequest myRequest = WebRequest.Create(url); WebResponse myResponse = myRequest.GetResponse(); myResponse.Close();

Now the above doesnt work but if I try to hit the url manually in this way it works-

"http://www.myurl.com/Key/1234?name=Test&address=test&contactno=1234

Can anyone tell me what am I doing wrong here ?


Solution

  • In this case, "myobject" automatically calls its ToString() method, which returns the type of the object as a string.

    You need to pick each property and add it to the querystring together with its value. You can use the PropertyInfo class for this.

    foreach (var propertyInfo in myobject.GetType().GetProperties())
    {
         url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(myobject, null));
    }
    

    The GetProperties() method is overloaded and can be invoked with BindingFlags so that only defined properties are returned (like BindingFlags.Public to only return public properties). See: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx