如何获取字节数组内容

时间:2019-01-11 19:43:29

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

我正在尝试编写一个将返回文件内容的webapi服务。在调用服务中,我似乎无法获得实际的文件内容,仅是内容头(在ByteArrayContent中)

我试图读取文件并创建适当的响应消息。当呼叫服务收到http响应并执行ReadAsByteArrayAsync()时,我获得的唯一数据实际上是http响应标头。

    [HttpGet]
    [Route("{type}")]
    public async Task<HttpResponseMessage> GetFile(string type, string fileName)
    {
        try
        {
            var filePath = @"...\" + fileName;

            var stream = new MemoryStream();
            var fileStream = System.IO.File.OpenRead(filePath);
            stream.SetLength(fileStream.Length);
            await fileStream.ReadAsync(stream.GetBuffer(), 0, (int)fileStream.Length);
            stream.Position = 0;

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(stream.ToArray())
            };
            response.Content.Headers.ContentLength = stream.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            return response;
        }
        catch (KeyNotFoundException)
        {
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }

当我在发送之前检查响应时,这看起来是正确的:

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.ByteArrayContent, Headers:{ Content-Length: 222772 Content-Disposition: attachment; filename=blablablah.JPG Content-Type: application/octet-stream}}

当我查看调用webapi的服务端

var httpResponse = await httpClient.GetAsync(builder.ToString());
var image = await httpResponse.Content.ReadAsByteArrayAsync();

if (image != null && image.Length > 0)
{
    var x = Encoding.Default.GetString(image);

    return result;
}

httpResponse是:

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{ Transfer-Encoding: chunked X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcRmlsZVN0cmVhbUFwaVxGaWxlU3RyZWFtQXBpXGFwaVxGaWxlXGV4cGVuc2VyZWNlaXB0?= Date: Fri, 11 Jan 2019 19:39:54 GMT Server: Kestrel X-Powered-By: ASP.NET Content-Type: application/json; charset=utf-8}}

,实际内容(来自ReadAsByteArrayAsync())是

"{\"version\":{\"major\":1,\"minor\":1,\"build\":-1,\"revision\":-1,\"majorRevision\":-1,\"minorRevision\":-1},\"content\":{\"headers\":[{\"key\":\"Content-Length\",\"value\":[\"222772\"]},{\"key\":\"Content-Disposition\",\"value\":[\"attachment; filename=47670af0-1916-4257-bbc2-b5f7da4c4839.JPG\"]},{\"key\":\"Content-Type\",\"value\":[\"application/octet-stream\"]}]},\"statusCode\":200,\"reasonPhrase\":\"OK\",\"headers\":[],\"requestMessage\":null,\"isSuccessStatusCode\":true}"

0 个答案:

没有答案