如果我有一个网页做这样的事情,
protected void Page_Load(object sender, EventArgs e)
{
List<string> items = new List<string>()
{
"test1",
"test2",
"test3"
};
Response.Write(items);
}我如何在另一端返回列表,例如,我在另一端有一些代码,
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:50513/Default.aspx");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
}我怎么才能把这个列表拉回来呢?
我必须使用一个asp的.net页面,因为与第三方API的限制,我必须使用。
发布于 2010-02-24 15:28:17
要进一步扩展Joe的回答,最好的方法是使用JSON.NET来序列化和反序列化列表。由于web只能来回发送字符串,因此JSON非常适合在web上发送对象。您可以像这样序列化列表(使用JSON.NET):
List<string> items = new List<string>()
{
"test1",
"test2",
"test3"
};
var json = JsonConvert.SerializeObject(items);
Response.Write(json);这将写入到响应中:
["test1", "test2", "test3"]在接收端,使用:
var list = JsonConvert.DeserializeObject<List<string>>(json);你会拿回你的原始列表。至于图标,如果你不能传递链接,实际上需要传递图标本身,你可以将文件序列化为base64编码的字符串(然后解码它),或者你可以使用BSON:
http://james.newtonking.com/archive/2009/12/26/json-net-3-5-release-6-binary-json-bson-support.aspx
我自己没有这样做过,所以我不能提供一个例子,对不起。
发布于 2010-02-24 10:23:27
如果你被绑定到使用响应(例如,不能使用WCF),你可以这样做,但是,除非你做了更多的事情,上面的响应将是列表的类型,而不是内容(items.ToString()将被写入流,据我所知,你将需要迭代元素并逐个写入它们)
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:50513/Default.aspx");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using(var responseStreamReader = new StreamReader(response.GetResponseStream())
{
var response = responseStreamReader.ReadToEnd();
//do deserialization hereh
}
}发布于 2010-02-24 10:28:44
您必须将列表序列化为一种格式,然后可以将其反序列化为消费端的列表。在JSON中有很多方法可以做到这一点,一种方法是使用JSON.NET作为.NET的格式。这样,您就不会受到谁可以使用数据的限制。其他格式可以是XML,也可以使用.NET内置的序列化程序之一。
示例:
服务器端:
List<string> items = new List<string>()
{
"test1",
"test2",
"test3"
};
string itemsString = JsonConvert.SerializeObject(items);
Response.Write(itemsString);客户端:
WebClient webRequest = new WebClient()
string json = webRequest.DonwloadString("http://localhost:50513/Default.aspx");
List<string> items = JsonConvert.DeserializeObject<List<string>>(json);https://stackoverflow.com/questions/2323229
复制相似问题