使用HttpClient进行流任务

时间:2018-01-26 21:05:55

标签: c# asp.net-mvc async-await dotnet-httpclient

我有这个返回任务的方法:

public async Task<Stream> GetPDF(string docPath) {
    if (String.IsNullOrWhiteSpace(docPath))
        return null;

    docPath = HttpUtility.UrlDecode(docPath.Replace('~', '%'));

    if (docPath.Contains(".."))
        return null;

    var url = ServiceUrl + "api/Document/PDF?docPath=" + docPath;

    using (HttpResponseMessage response = await client.GetAsync(url))
    using (Stream mystream = await response.Content.ReadAsStreamAsync()) {
        return mystream;
    }
}

我称之为:

public async Task<ActionResult> Render(int documentID) {
    // code to get path from documentID is omitted
    Task<Stream> dataStream = GetPDF(document.DocumentPath);
    return File(dataStream, "application/pdf");
}

但是,这不能编译,因为您无法从任务转换为字节。如何提取mystream?

1 个答案:

答案 0 :(得分:0)

首先,当方法超出范围时,将处理流。不要丢弃流。

public async Task<Stream> GetPDF(string docPath) {
    if (String.IsNullOrWhiteSpace(docPath))
        return null;

    docPath = HttpUtility.UrlDecode(docPath.Replace('~', '%'));

    if (docPath.Contains(".."))
        return null;

    var url = ServiceUrl + "api/Document/PDF?docPath=" + docPath;

    using (var response = await client.GetAsync(url)) {
        return await response.Content.ReadAsStreamAsync();            
    }
}

接下来,在调用方法时,您可以等待它

public async Task<ActionResult> Render(int documentID) {
    //...code to get path from documentID is omitted
    Stream dataStream = await GetPDF(document.DocumentPath);
    return File(dataStream, "application/pdf");
}