views:

22

answers:

3

Hi all,

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 ?

+1  A: 

I would recommend defining how to turn MyObject into query string values. Make a method on the object which knows how to set properties for all of its values.

public string ToQueryString()
{
    string s = "name=" + this.name;
    s += "&address=" + this.address;
    s += "&contactno=" + this.contactno;
    return s
}

Then instead of adding myObject, add myObject.ToQueryString().

Brendan Enrick
+1  A: 

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

KBoek
A: 

Here is the tostring method I wrote -

public override string ToString()
    {
        Type myobject = (typeof(MyObject));
        string url = string.Empty;
        int cnt = 0;
        foreach (var propertyInfo in myobject.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            if (cnt == 0)
            {
                url += string.Format("{0}={1}", propertyInfo.Name, propertyInfo.GetValue(this, null));
                cnt++;
            }
            else
                url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(this, null));
        }
        return url;
    }
Misnomer