Come pubblicare un oggetto definito utente personalizzato su un URL?
-
25-09-2019 - |
Domanda
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 ();
Ora quanto sopra non funziona ma se provo a colpire l'URL manualmente in questo modo funziona-
"http://www.myurl.com/Key/1234?name=Test&address=test&contactno=1234
Qualcuno può dirmi cosa sto facendo di sbagliato qui?
Soluzione
In questo caso, "MyObject" chiama automaticamente il suo metodo ToString (), che restituisce il tipo di oggetto come stringa.
È necessario scegliere ogni proprietà e aggiungerla alla querystring insieme al suo valore. È possibile utilizzare la classe PropertyInfo per questo.
foreach (var propertyInfo in myobject.GetType().GetProperties())
{
url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(myobject, null));
}
Il metodo GetProperties () è sovraccarico e può essere invocato con BindingFlags in modo da restituire solo le proprietà definite (come BindingFlags.Public per restituire solo proprietà pubbliche). Vedere: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx
Altri suggerimenti
Consiglierei di definire come trasformare MyObject in valori di stringa di query. Crea un metodo sull'oggetto che sa come impostare le proprietà per tutti i suoi valori.
public string ToQueryString()
{
string s = "name=" + this.name;
s += "&address=" + this.address;
s += "&contactno=" + this.contactno;
return s
}
Quindi invece di aggiungere myObject, aggiungi myObject.toquerystring ().
Ecco il metodo toString che ho scritto -
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;
}