WebApi文件下载首次冻结了浏览器

时间:2015-12-24 11:37:14

标签: c# asp.net-web-api asp.net-web-api2

我正在使用WebAPI下载.pdf文件,如下所示:

[HttpGet]
public async Task<HttpResponseMessage> DownloadFile(string id, bool attachment = true)
{
    HttpResponseMessage result = null;

    try
    {
        MyService service = new MyService();
        var bytes = await service.DownloadFileAsync(id);

        if (bytes != null)
        {
            result = GetBinaryFile(personalDocument, string.Format("{0}.pdf", id), attachment);
        }
        else
        {
            result = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
    catch (Exception ex)
    {
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "ServerError" });
    }

    return result;
}

private HttpResponseMessage GetBinaryFile(byte[] bytes, string fileName, bool attachment)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
   // result.Content = new ByteArrayContent(bytes);
    result.Content = new StreamContent(new System.IO.MemoryStream(bytes));
    //result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");

    if (attachment)
    {
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    }

    result.Content.Headers.ContentDisposition.FileName = fileName;
    result.Content.Headers.ContentLength = bytes.Length;
    return result;
}

问题是:当我第一次下载文件时,它会冻结浏览器,并且无法执行任何操作。但刷新页面后,每次文件下载成功。

我尝试使用ByteArrayContentStreamContent,但同样的事情发生了。我还尝试使用MediaTypeHeaderValue("application/octet-stream")MediaTypeHeaderValue("application/pdf"),但又一次 - 发生了同样的问题。

所以我发现问题是

if (attachment)
{
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}

如果我将附件设置为true,则将ContentDisposition设置为ContentDispositionHeaderValue("attachment")(仅供下载)

如果我将附件设置为false,则立即打开文件,不会冻结浏览器..

有什么想法吗?谢谢!

0 个答案:

没有答案