【发布时间】:2018-02-09 11:33:01
【问题描述】:
我有一个 txt 文件,里面有一些数据。我想以 JSON 格式返回数据。
为什么当我在控制器中执行此操作时,我能够显示结果(但不是 JSON 格式):
public IHttpActionResult Get()
{
return new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
}
但是,当我这样做时,我得到的结果是:{"Data":{}}
public IHttpActionResult Get()
{
var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
return Ok(new { Data = result });
}
如果我只是return result:
public IHttpActionResult Get()
{
var result = (new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt"));
return result;
}
我确实得到了数据,但是它不是我想要的 Json 格式,例如{"Data": "Allthecontentinhere"}。我试过return Json(result) 也没有用。
这是我的 FileReaderClient.cs 类
public class FileReaderClient : IHttpActionResult
{
private readonly string filePath;
private readonly string contentType;
public FileReaderClient(string filePath, string contentType = null)
{
this.filePath = filePath;
this.contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(filePath))
};
var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}, cancellationToken);
}
}
如何编辑我的代码以使文件中的数据以 JSON 格式返回?
【问题讨论】:
-
由于您使用 WebAPI 控制器(与支持
Json()方法的 ASP.Net MVC 控制器相比)返回合理的对象应自动生成 JSON 响应。在帖子的当前状态下,无法知道您想要实现什么以及为什么您的自定义FileReaderClient不代表您想要的数据。考虑阅读minimal reproducible example 发布代码指南和edit 帖子以澄清。 -
嗨,我已经包含了我的 FileReaderClient 类
-
为什么不使用 Server.Mappath——使用像“C:\\Users\\attsuap1\\Desktop\\1milliontest.txt”这样的路径不是一个好习惯,Okey 可能不是你没有得到 JSON 的实际原因,但它仍然表明你没有把 100% 放在你的代码中。
-
我一开始使用它并得到一个错误
Physical Path given but virtual path expected。然后我读到当我知道stackoverflow答案之一中的路径时不需要Server.Mappath -
如果我将您的代码与
return result一起使用,我会得到一个有效的 JSON。你得到了什么?你说:“我确实得到了数据,但它不是 Json 格式”.