Web Api 2没有将ByteArrayContent返回给HTTPClient

时间:2016-03-24 14:12:33

标签: c# winforms asp.net-web-api2 dotnet-httpclient

我正在win form表单中使用WebApi2和HttpClient组合测试应用程序。

我遇到了一个问题,我的HttpClient请求返回HttpResponseMessage的WebApi2控制器不会返回ByteArrayContent。 WebApiController代码

[HttpGet]
public HttpResponseMessage DownloadFilePart(string fileName)
{
    var path = Server.MapPath("~/App_Data/uploads/" + fileName);
    var fileArray = System.IO.File.ReadAllBytes(path);

    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new  ByteArrayContent(fileArray)
    };

    response.Content.Headers.ContentType = new MediaTypeHeaderValue(System.Web.MimeMapping.GetMimeMapping(fileName));
    response.Content.Headers.ContentLength = fileArray.Length;
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = fileName
    };

    return response;
}

使用HttpClient的WinForms代码

static async void GetFilePart(string hostrUri)
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri(hostrUri)
    };

    var request = new HttpRequestMessage(HttpMethod.Get, "/Home/DownloadFilePart/?fileName=Test.txt");
    var responseMessage = httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
    var memoryStream = new MemoryStream();
    var stream = await responseMessage.Result.Content.ReadAsByteArrayAsync();
    var fileToWriteTo = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\Temp\\Test.txt";

    using (var fileStream = new FileStream(fileToWriteTo, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        //copy the content from response to filestream
        fileStream.Write(stream, 0, stream.Length);
    }
}

当请求从WebApi返回并将字节写入文件时,写入文件的所有内容都是来自WebApi响应的实际标头。有没有人知道这个问题可能在这里?

由于

1 个答案:

答案 0 :(得分:2)

你的问题在这里

httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

HttpCompletionOption.ResponseHeadersRead总结为

  

一旦响应可用并且读取标题,操作就应该完成。 内容尚未阅读

这可以解释为什么您只能在回复中获得标题。

完全删除它或将其更改为HttpCompletionOption.ResponseContentRead

static async void GetFilePart(string hostrUri)
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri(hostrUri)
    };

    var request = new HttpRequestMessage(HttpMethod.Get, "/Home/DownloadFilePart/?fileName=Test.txt");
    var responseMessage = await httpClient.SendAsync(request);
    var byteArray = await responseMessage.Content.ReadAsByteArrayAsync();
    var fileToWriteTo = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\Temp\\Test.txt";

    using (var fileStream = new FileStream(fileToWriteTo, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        //copy the content from response to filestream
        fileStream.Write(byteArray, 0, byteArray.Length);
    }
}