如何从ASP.Net API调用返回文件?

时间:2017-01-03 10:37:27

标签: asp.net api asp.net-web-api

我已经阅读了很多答案,过去几周一直在网上搜索,试图找到答案。

我读过:How to return a file (FileContentResult) in ASP.NET WebAPI
并且:Returning binary file from controller in ASP.NET Web API

当我调试时,它会不断地回调,一遍又一遍地运行该方法。 在服务器(IIS)上运行时,根据浏览器的不同,会显示一条消息This site can’t be reached,或者它会下载文件,但表明下载有问题。

我正在使用的代码是

    <HttpGet, Route("api/Reports/Create")>
    Public Function CreateReport() As HttpResponseMessage
        Dim data = GetReportBuffer()

        'This is just for testing
        'To check that the report is created correctly
        'I can open up temp.pdf, it is fine
        Using fs As New FileStream("c:\temp\temp.pdf", FileMode.Create)
            data.CopyTo(fs)
            fs.Flush()
            fs.Close()
        End Using

        Dim result = Request.CreateResponse(HttpStatusCode.OK)
        'This should be StreamContent(data... but using this for testing
        result.Content = New StreamContent(New FileStream("c:\temp\temp.pdf", FileMode.Open))
        result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
        result.Content.Headers.ContentDisposition = New ContentDispositionHeaderValue("attachment") With {.FileName = $"{fllId}.{ext}"}

        Return result
    End Function

我也尝试过ByteArrayContent,但结果完全一样。 我有什么不正确的事吗?

0 个答案:

没有答案