以前的答案是正确的:添加行...
Response.AddHeader("Content-Disposition", "inline; filename=[filename]");
...将导致多个 Content-Disposition 标头被发送到浏览器。FileContentResult
如果您为其提供文件名,则会发生这种情况 b/c在内部应用标题。另一种非常简单的解决方案是简单地创建一个子类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);
}
}
在 yourController
或 baseController
中,您可以编写一个简单的助手来实例化 a 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
});
}
现在,该文件将使用您选择的文件名和“inline; filename=[filename]”的内容处置标头发送到浏览器。
我希望这会有所帮助!