我正在使用this将我的客户端应用程序挂接到我的Web服务中。
另外,我是looking at MSDN关于读取第一个链接的GetResponse。从Web服务读取响应数据
下面是我到目前为止已经获得了代码:
public ActionResult Index()
{
WebRequest request = WebRequest.Create("http://localhost:49474/api/Store/Get");
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stores = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader(stores, encode);
Char[] read = new Char[1024];
int count = sr.Read(read, 0, 1024);
List<Store> storesList = new List<Store>();
while (count > 0)
{
// need to read the contents of the response strem into the above instantiated list of stores.
}
}
我的API提供的数据是这样的:
public HttpResponseMessage Get()
{
List<Store> stores = db.Stores.ToList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, stores);
return response;
}
坦率地说,我不知道接下来要去哪里。 MSDN链接将其全部写入字符串,但我的担忧是:
- 我怎么知道每次需要为每条记录读取多少个字符?
- 如何读取API发送的数据以便我可以在我的视图中使用它?
你打算使用第三方库吗?如果是这样,你可能想尝试类似[RestSharp](http://restsharp.org/) –
我假设我在客户端应用程序中使用它,现在正在编写使用Web服务中的数据? – Ortund
是的,你在客户端使用它。它会自动读取和反序列化您的响应数据,只要它被序列化为JSON或XML。 –