以前的答案是正确的:添加行...
Response.AddHeader("Content-Disposition", "inline; filename=[filename]");
...将导致多个Content-Disposition标题被发送到浏览器。发生这种情况b/c FileContentResult
内部应用标题,如果您提供一个文件名称。另一种简单的解决方法是简单地创建FileContentResult
的子类并覆盖其ExecuteResult()
方法。下面是实例化System.Net.Mime.ContentDisposition
类(在内部FileContentResult
实现中使用相同的对象)的一个实例,并将其传递到新类的例子:
public class FileContentResultWithContentDisposition : FileContentResult
{
private const string ContentDispositionHeaderName = "Content-Disposition";
public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
: base(fileContents, contentType)
{
// check for null or invalid ctor arguments
ContentDisposition = contentDisposition;
}
public ContentDisposition ContentDisposition { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
// check for null or invalid method argument
ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
var response = context.HttpContext.Response;
response.ContentType = ContentType;
response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
WriteFile(response);
}
}
在你Controller
,或在基础Controller
,你可以写一个简单的辅助来实例化一个FileContentResultWithContentDisposition
,然后从你的行动方法调用它,就像这样:
protected virtual FileContentResult File(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
{
var result = new FileContentResultWithContentDisposition(fileContents, contentType, contentDisposition);
return result;
}
public ActionResult Report()
{
// get a reference to your document or file
// in this example the report exposes properties for
// the byte[] data and content-type of the document
var report = ...
return File(report.Data, report.ContentType, new ContentDisposition {
Inline = true,
FileName = report.FileName
});
}
现在,该文件将被发送到与文件名的浏览器选择和使用的内容处置头“内联;文件名= [文件名]“。
我希望有帮助!
黑客,但非常有效的黑客!谢谢! – 2013-10-15 01:17:37
不幸的是,IE 11仍然需要。Chrome和Firefox不需要。 – 2016-01-25 09:47:58