我正在研究如何从jQuery ajax调用从ASP.NET Web Api下载CSV文件。CSV文件是基于自定义CsvFormatter从Web API服务器动态生成的。
来自jQuery的Ajax:
$.ajax({
type: "GET",
headers: {
Accept: "text/csv; charset=utf-8",
},
url: "/api/employees",
success: function (data) {
}
});
在服务器上,从BufferedMediaTypeFormatter
派生的EmployeeCsvFormatter
实现方式类似于下面的文章
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
public class EmployeeCsvFormatter : BufferedMediaTypeFormatter
{
public EmployeeCsvFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
}
...
}
我还添加了覆盖方法,以表明我想以正常的方式下载文件(可以在下载选项卡中看到下载文件):
public override void SetDefaultContentHeaders(Type type,
HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.Add("Content-Disposition", "attachment; filename=yourname.csv");
headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
但它不工作,下载文件没有显示在状态栏或在Chrome的下载选项卡中,即使从Fiddler,我看到它的响应似乎是正确的:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Mon, 11 Mar 2013 08:19:35 GMT
X-AspNet-Version: 4.0.30319
Content-Disposition: attachment; filename=yourname.csv
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/octet-stream
Content-Length: 26
Connection: Close
1,Cuong,123
1,Trung,123
我在ApiController中的方法:
public EmployeeDto[] Get()
{
var result = new[]
{
new EmployeeDto() {Id = 1, Name = "Cuong", Address = "123"},
new EmployeeDto() {Id = 1, Name = "Trung", Address = "123"},
};
return result;
}
它一定是错在什么地方,我还没弄清楚。如何才能像正常方式一样下载CSV文件?
https://stackoverflow.com/questions/15334227
复制相似问题