【问题标题】:How to post a custom user defined object to a url?如何将自定义用户定义的对象发布到 url?
【发布时间】:2011-04-05 20:17:49
【问题描述】:
我的对象我的对象=新的我的对象();
myobject.name="测试";
myobject.address="测试";
myobject.contactno=1234;
字符串 url = "http://www.myurl.com/Key/1234?" +我的对象;
WebRequest myRequest = WebRequest.Create(url);
WebResponse myResponse = myRequest.GetResponse();
myResponse.Close();
现在上述方法不起作用,但如果我尝试以这种方式手动点击 url,它会起作用-
"http://www.myurl.com/Key/1234?name=Test&address=test&contactno=1234
谁能告诉我我在这里做错了什么?
【问题讨论】:
标签:
post
webrequest
webresponse
custom-object
【解决方案1】:
我建议定义如何将 MyObject 转换为查询字符串值。在对象上创建一个方法,该方法知道如何为其所有值设置属性。
public string ToQueryString()
{
string s = "name=" + this.name;
s += "&address=" + this.address;
s += "&contactno=" + this.contactno;
return s
}
然后,不要添加 myObject,而是添加 myObject.ToQueryString()。
【解决方案2】:
在这种情况下,“myobject”会自动调用其 ToString() 方法,该方法将对象的类型作为字符串返回。
您需要选择每个属性并将其与其值一起添加到查询字符串中。您可以为此使用 PropertyInfo 类。
foreach (var propertyInfo in myobject.GetType().GetProperties())
{
url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(myobject, null));
}
GetProperties() 方法被重载,可以使用 BindingFlags 调用,以便只返回定义的属性(如 BindingFlags.Public 只返回公共属性)。见:http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx
【解决方案3】:
这是我写的tostring方法——
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;
}