从 byte[] 下载文件 C# MVC

Lar*_*ers 2 .net c# asp.net-mvc-5

我正在尝试从字节数组下载文件,但提示似乎没有进行下载。我需要包含额外的 ContentDisposition 属性吗?如果我查看 IE 中的网络流量,我可以看到文件请求有效并且返回 200,此外我还可以从 IE 调试工具内容下载文件。

存储在字节数组中的文件是一个 Word 文档。我已将 MIME 类型设置为:

应用程序/vnd.openxmlformats-officedocument.wordprocessingml.document

并且文档文件名是:QuickStartGuide.docx

以及为什么不显示下载提示的想法?

[HttpPost]
[ValidateAntiForgeryToken]
public FileContentResult DocumentDownload(int documentId)
{
    try
    {
        var document = BusinessLayer.GetDocumentsByDocument(documentId, AuthenticationHandler.HostProtocol).FirstOrDefault();

        System.Net.Mime.ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition();

        contentDisposition.FileName = document.FileName;
        contentDisposition.Inline = false;

        var result = new FileContentResultWithContentDisposition(document.FileBytes, document.FileType, contentDisposition);

        return result;
    }
    catch
    {
        throw;
    }
}


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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ral*_*ing 8

你的action方法被修饰为POST,但是文件下载有GET操作,下载也不需要防伪验证。

ASP.NET MVC 框架已经内置了FileResult. MVC 控制器本身具有便利功能File(...)https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.file(v=vs.118).aspx

为了通知浏览器下载文件,您必须指定内容类型和下载文件名。这会将您的代码缩短为:

[HttpGet]
public FileResult DocumentDownload(int documentId)
{
    var document = BusinessLayer.GetDocumentsByDocument(documentId, AuthenticationHandler.HostProtocol).FirstOrDefault();

    return File(document.FileBytes, document.FileType, document.FileName);           
}
Run Code Online (Sandbox Code Playgroud)