我试图从服务器端返回一个字符串数组并从客户端检索它。这就是我的服务器端的样子:
[HttpGet]
public string[] GetFileNameList()
{
//get file names from the Directory
string[] files = Directory.GetFiles(@"C:\Users\ndmendis\Desktop\files\in", "*.txt");
return files;
}
我的客户端是这样的:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:59831/Home/GetFileNameList/");
request.ContentType = "application/text";
request.Proxy = null;
request.KeepAlive = false;
//request.ContentLength = 0;
request.Method = "GET";
var response = request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
// Read the content.
string responseFromServer = reader.ReadToEnd();
String[] str = responseFromServer.Cast<string>().Cast<string>().ToArray();
从客户端,我正在尝试通过 http 访问服务器,并且它有效。它转到我的服务器端。服务器端完美地返回了字符串数组。 但问题是我没有获得该字符串数组的正确内容(我的 'responseFromServer' 变量值为字符串 [])。 'responseFromServer' 变量应该包含我传递的值。有人可以解决我遇到的问题吗?谢谢!
显然在响应变量中有一个名为 segment 的标签。所有值(我从服务器发送的值)都在其中,但我的流似乎不包含这些值...
最佳答案
不能评论(没有足够的声誉)。 但请尝试以下将整个响应流读取为字节数组,然后将其反序列化(使用 .Net 序列化类)转换为字符串数组(对象)。
编辑: 我在默认的 WebApi Values Controller 上构建了这个示例,它顺便也返回了一个字符串数组。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
var url = "http://localhost:14596/api/values";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Accept] = "application/json";
byte[] result = client.DownloadData(url);
// now use a JSON parser to parse the resulting string back to some CLR object
string[] resultArr = parse(result);
}
}
public static string[] parse(byte[] json)
{
string jsonStr = Encoding.UTF8.GetString(json);
return JsonConvert.DeserializeObject<string[]>(jsonStr);
}
}
}
关于c# - 如何从流中获取字符串数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32962116/