以JSON

时间:2017-12-21 06:40:34

标签: c# json

我有一个包含一些数据的txt文件。我有一些代码允许Web浏览器在txt文件中显示数据。我希望数据以JSON格式显示。

这是我的代码

FileReaderClient.cs

public class FileReaderClient : IHttpActionResult
{        
    public string filePath;       
    public FileReaderClient(string filePath)
    {
        this.filePath = filePath;           
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.Run(() =>
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(File.OpenRead(filePath))
            };

            return response;
        });
    }
}

FileReaderController.cs

public IHttpActionResult Get()
    {
        var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\testfile.txt" );
        return result;
    }

当我return result;时,我会在网络浏览器中显示我的txt文件中的数据。但是,当我尝试以JSON格式返回return Json(result);时,我得到的结果为{"filePath":"C:\\Users\\attsuap1\\Desktop\\testfile.txt"},而不是我的txt文件中的数据。为什么会这样?如何在Web浏览器上以JSON格式显示txt文件中的数据?

有人请帮助我,并提前感谢你。

1 个答案:

答案 0 :(得分:2)

尝试以下方法将文件内容作为回复发送回来

[HttpGet]//http get as it return file 
        public HttpResponseMessage GetTextFile()
        {
            //below code locate physcial file on server 
            var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.txt");
            HttpResponseMessage response = null;
            if (!File.Exists(localFilePath))
            {
                //if file not found than return response as resource not present 
                response = Request.CreateResponse(HttpStatusCode.Gone);
            }
            else
            {
                string data = string.Join(" ", File.ReadAllLines(localFilePath));
                response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(data, Encoding.UTF8, "text/html")
                };
            }
            return response;
        }

您正面临错误,因为您尝试使用物理路径访问文件..您需要使用Server.MapPath函数访问文件..当您使用webpi或Web应用程序时。

你必须这样做,在webAPI中创建文件夹并将文件放在该文件夹中。

 string pathToFiles = Server.MapPath("~/files/testfile.txt");

例如,请点击此处:https://www.dotnetperls.com/mappath