C# 以JSON格式返回时,文件中的数据不会显示在web浏览器中

C# 以JSON格式返回时,文件中的数据不会显示在web浏览器中,c#,json,C#,Json,我有一个包含一些数据的txt文件。我有一些代码,允许网络浏览器在txt文件中显示数据。我希望数据以JSON格式显示 这是我的密码 FileReaderClient.cs public class FileReaderClient : IHttpActionResult { public string filePath; public FileReaderClient(string filePath) { this.filePa

我有一个包含一些数据的txt文件。我有一些代码,允许网络浏览器在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;
        });
    }
}
public IHttpActionResult Get()
    {
        var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\testfile.txt" );
        return result;
    }
当我执行
返回结果时我在web浏览器中显示的txt文件中获取数据。然而,当我尝试以JSON格式返回它时,
返回JSON(结果),我得到的结果是
{“filePath”:“C:\\Users\\attsuap1\\Desktop\\testfile.txt”}
而不是我的txt文件中的数据。为什么会这样?我应该如何在web浏览器上以JSON格式显示txt文件中的数据


有人请帮助我,并提前向您表示感谢。

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

[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");

例如,请检查此处:

您是否可以尝试我建议的方式,并让我知道是否为您工作。我创建了文件文件夹,但它未显示在解决方案资源管理器中,是否可以?我刷新了一百万次times@SushaNaidu-尝试发送我在代码中给出的详细信息所有这些代码都在controller或FileReaderClient.cs下?我的意思是它应该在controller或FileReaderClient.cs下吗?当我输入这些代码时,我会出错confused@SushaNaidu-我应该转到这里:公共任务ExecuteAsync(CancellationToken CancellationToken)