Vb.net webapi文件下载麻烦

时间:2015-12-11 23:52:28

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

我们一直在使用IIS文件处理程序来下载存储在PowerPoint等数据库中的文件。现在我们正在尝试切换到webapi。文件上传工作正常,但下载不是。

使用文件处理程序,url就像:http://localhost:57851/docmgr?id=6202,它返回一个有效文件,其中包含来自Fiddler的以下信息: filehandler

在网址为http://localhost:57851/webapi/file/GetFile?id=6202的网址控制器中使用相同的代码会返回添加了额外字节的文件。提琴手数据: webapi

请注意内容类型的更改,即使内容类型明确设置为" application / vnd.ms-powerpoint"。

我一定错过了什么......

这是控制器代码:

<HttpGet>
Public Function GetFile()
    Dim dbConn As New SqlConnection(DigsConnStr)
    Dim dbCmd As New SqlCommand
    Dim dbRdr As SqlDataReader
    Dim id As String = HttpContext.Current.Request.QueryString("id")
    Dim bytes As Byte()
    Dim contentType As String
    Dim fileName As String
    Dim fileExt As String

    Try
        dbConn.Open()
        dbCmd.Connection = dbConn
        dbCmd.CommandText = "GET_FileForDownload"
        dbCmd.CommandType = CommandType.StoredProcedure
        dbCmd.Parameters.AddWithValue("@VirtualFileRecID", id)
        dbRdr = dbCmd.ExecuteReader
        dbRdr.Read()
        contentType = dbRdr("ContentType")
        bytes = dbRdr("FileBytes")
        fileExt = dbRdr("FileExtension")
        If contentType <> "" Then
            fileName = dbRdr("Title") & fileExt
            HttpContext.Current.Response.ContentType = contentType
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
            HttpContext.Current.Response.BinaryWrite(bytes)
            'HttpContext.Current.Response.Flush()

        End If
        dbConn.Close()
    Catch ex As Exception
        dbConn.Close()
    Finally
        If Not (dbConn Is Nothing) Then dbConn.Close()
    End Try
End Function

1 个答案:

答案 0 :(得分:2)

WebAPI将用XML(或您在webapiconfig类中的任何格式化程序)包装您的响应

您真的不应该直接使用WebAPI访问响应流,但是您可以使用文件流返回HttpResponseMessage对象

检查出来

<HTTPGET>
Public Function GetFile(FileID as Integer) As HttpResponseMessage
 Dim path = "C:\Temp\test.exe"
 Dim result As New HttpResponseMessage(HttpStatusCode.OK)
 Dim stream = New FileStream(path, FileMode.Open)

 result.Content = New StreamContent(stream)
 result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")

 Return result
End Function

然后您应该像这样访问它:http://localhost:57851/docmgr/6202