Post 如何将自定义用户定义的对象发布到url?
MyObject MyObject=新的MyObject(); myobject.name=“测试”; myobject.address=“测试”; myobject.contactno=1234; 字符串url=“?”+myobject; WebRequest myRequest=WebRequest.Create(url); WebResponse myResponse=myRequest.GetResponse(); myResponse.Close() 现在,上面的方法不起作用,但是如果我尝试用这种方式手动点击url,它就会起作用-Post 如何将自定义用户定义的对象发布到url?,post,webrequest,webresponse,custom-object,Post,Webrequest,Webresponse,Custom Object,MyObject MyObject=新的MyObject(); myobject.name=“测试”; myobject.address=“测试”; myobject.contactno=1234; 字符串url=“?”+myobject; WebRequest myRequest=WebRequest.Create(url); WebResponse myResponse=myRequest.GetResponse(); myResponse.Close() 现在,上面的方法不起作用,但是如果
"http://www.myurl.com/Key/1234?name=Test&address=test&contactno=1234
有人能告诉我我做错了什么吗?我建议定义如何将MyObject转换为查询字符串值。在对象上创建一个知道如何为其所有值设置属性的方法
public string ToQueryString()
{
string s = "name=" + this.name;
s += "&address=" + this.address;
s += "&contactno=" + this.contactno;
return s
}
然后,不添加myObject,而是添加myObject.ToQueryString()。在本例中,“myObject”自动调用其ToString()方法,该方法以字符串形式返回对象的类型
您需要拾取每个属性,并将其与其值一起添加到querystring中。您可以为此使用PropertyInfo类
foreach (var propertyInfo in myobject.GetType().GetProperties())
{
url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(myobject, null));
}
GetProperties()方法是重载的,可以使用BindingFlags调用,以便只返回已定义的属性(如BindingFlags.Public仅返回公共属性)。请参阅:以下是我编写的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;
}