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 any开发者_JS百科one tell me what am I doing wrong here ?
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
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().
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;
}
精彩评论