在我的ASP.NET WebAPI项目中,我需要将字符串JSON数据作为文件返回。我希望将响应设置的状态代码设置为200(成功)也很重要。我找到了许多示例,人们使用MemoryStream和FileStreamResult从服务器获取适当的文件,但对我不起作用。
不幸的是,我总是在浏览器中收到消息,即"意外错误",尽管SERWER代码工作没有任何例外。我在浏览器中检查了请求的详细信息,并具有状态代码"不良请求"(400)。
我的代码:
[HttpGet()]
public async Task<IActionResult> Download()
{
string jsonData = "example data";
byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
var stream = new MemoryStream(byteArray);
var result = new FileStreamResult(stream, new MediaTypeHeaderValue("text/json"))
{
FileDownloadName = "testFile.json"
};
return result;
}
[HttpGet()]
public async Task<HttpResponseMessage> Download()
{
string jsonData = "example data";
byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new ByteArrayContent(byteArray)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(Inline) { FileName = "testFile.json" };
return result;
}