从.NET Core控制器返回CSV [英] Returning CSV from .NET Core controller
问题描述
我无法将.NET Core API Controller端点解析为CSV下载.我正在使用从.NET 4.5控制器中提取的以下代码:
I'm having trouble having a .NET Core API Controller endpoint resolve to a CSV download. I'm using the following code which I pulled from a .NET 4.5 controller:
[HttpGet]
[Route("{id:int}")]
public async Task<HttpResponseMessage> Get(int id)
{
string csv = await reportManager.GetReport(CustomerId, id);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(csv);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { FileName = "report.csv" };
return response;
}
当我从Angular 4应用程序中点击此端点时,我将以下响应写入浏览器:
When I hit this endpoint from my Angular 4 app, I get the following response written to the browser:
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"text/csv"
]
},
{
"key": "Content-Disposition",
"value": [
"attachment; filename=11.csv"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [ ],
"requestMessage": null,
"isSuccessStatusCode": true
}
我的期望是,当我点击端点时,将提示用户下载CSV.
My expectation is that when I hit the endpoint, the user will be prompted to download the CSV.
我发现了这篇帖子,内容涉及如何在.NET Core中导出" CSV.问题是我正在从源(AWS S3存储桶)中检索CSV内存,而此代码似乎仅在具有IEnumerable<object>
时才起作用.
I found this post on how to "export" a CSV in .NET Core. The problem is that I'm retrieving the CSV in-memory from it's source (an AWS S3 bucket) whereas this code seems to only work when you have an IEnumerable<object>
.
我想知道我的问题是否出在请求或响应头中,那是阻止浏览器从我的API检索CSV的原因.这是我在浏览器控制台中看到的内容:
I'm wondering if my problem lies in either request or response headers, where there is something preventing the browser from retrieving a CSV from my API. Here is what I see in the browser console:
推荐答案
强制下载文件而不是显示内联的正确方法是使用请参阅文档),已经指出,这可能会带来意想不到的副作用.
The proper way to force a file to be downloaded instead of displayed inline is using the Content-Disposition
response header. While the below solution works (see documentation) it's been pointed out that this can have unintended side effects.
将Content-Type
响应标头设置为application/octet-stream
将迫使大多数主流浏览器提示用户保存文件,而不是在窗口中显示.
Setting the Content-Type
response header to application/octet-stream
will force most major browsers to prompt the user to save the file instead of displaying it in the window.
尝试执行以下操作:
var result = new FileContentResult(myCsvByteArray, "application/octet-stream");
result.FileDownloadName = "my-csv-file.csv";
return result;
这篇关于从.NET Core控制器返回CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!