我使用针对4.5.2框架的ASP.NET Web API,并尝试推出通过从表导出数据生成的CSV文件。在Firefox和Chrome中,一切都按预期工作,但是使用IE(我用11测试),文件名被忽略,IE正在使用URL(没有扩展名)。我做错了什么,我怎么能解决它?
这是我的控制器方法:
[HttpGet]
public HttpResponseMessage ExportToCSV([FromUri]DistributionSearchCriteria criteria)
{
// This creates the csv in the temp folder and returns the temp file name
var file = _repository.ExportToCSV(criteria);
// This FileHttpResponseMessage is a custom type which just deletes the temp file in dispose
var result = new FileHttpResponseMessage(file, HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(file))
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "Distributions.csv"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
这是自定义FileHttpResponseMessage
public class FileHttpResponseMessage : HttpResponseMessage
{
private string _filePath;
public FileHttpResponseMessage(string filePath, HttpStatusCode statusCode) : base(statusCode)
{
_filePath = filePath;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
Content.Dispose();
if (File.Exists(_filePath))
{
try
{
System.Diagnostics.Debug.WriteLine("Deleting {0}", (object)_filePath);
File.Delete(_filePath);
System.Diagnostics.Debug.WriteLine("{0} deleted", (object)_filePath);
}
catch
{
System.Diagnostics.Debug.WriteLine("Error Deleting {0}", (object)_filePath);
}
}
}
}
}
这些是我在AngularJS控制器中启动下载的两种JavaScript方法:
vm.exportToCSV = function () {
var params = $httpParamSerializer(vm.searchCriteria);
$window.open(apiBase + 'Distribution/ExportToCSV?' + params, '_blank');
};
vm.exportAllToCSV = function () {
$window.open(apiBase + 'Distribution/ExportToCSV', '_blank');
};
从我在其他问题中读到的内容......设置附件; filename =应该足够IE了。 IE正在提示输入" ExportToCSV"。
的文件名我还尝试添加虚假参数,例如?/distribution.csv
,但它更改了下载文件名,但它取代了distribution.csv
,而.
替换为_
所以结果是distribution_csv
。哦,IE的痛苦。
更新1:
我已创建了一个单独的项目来解决此问题,并提出了具体的解决方法。我已尝试使用和不带引号的文件名,但我仍然没有区别:
更新2:
所以我想我会尝试成为聪明的"并尝试为扩展名为
的文件创建自定义HTTP处理程序的Web.config
<!-- Route all files through asp -->
<modules runAllManagedModulesForAllRequests="true" />
<!-- Route all files through asp -->
<add name="FileDownloadHandler" path="/api/File/test.csv" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
WebApiConfig.cs
config.Routes.MapHttpRoute(
name:"download",
routeTemplate: "api/File/test.csv",
defaults: new { controller = "File", action = "Get" }
);
正如预期的那样,它使用test.csv
,但它将.
替换为_
,从而导致test_csv
无扩展名下载。