c# - 如何从流中获取字符串数组值?

标签 c# arrays asp.net-mvc web

我试图从服务器端返回一个字符串数组并从客户端检索它。这就是我的服务器端的样子:

[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 的标签。所有值(我从服务器发送的值)都在其中,但我的流似乎不包含这些值...
enter image description here

最佳答案

不能评论(没有足够的声誉)。 但请尝试以下将整个响应流读取为字节数组,然后将其反序列化(使用 .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/

相关文章:

jquery - 至少选择一个复选框 - Asp.Net MVC - jQuery

c# - 如何将日期从 Model.FirstOrDefault() 转换为短日期格式

c# - 为什么我的 ASP.NET MVC 4 应用程序创建新实体而不是更新旧实体?

javascript - __doPostBack 不是一个函数

c# - 如何创建一个将泛型类作为参数的方法

python - 根据另一个索引数组重复 numpy 数组元素

java - 使用自定义排序功能实现 Treeset

c# - Visual Studio 2013 创建 Web API 项目时出错 : The element <#text> beneath element <Project> is unrecognized

c# - 检查参数类型

php - 通过点分隔键删除多维数组中的子树