【问题标题】:Task of Stream with HttpClientHttpClient 的 Stream 任务
【发布时间】:2018-07-06 06:35:39
【问题描述】:

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

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?

【问题讨论】:

  • 这可能对你有帮助:Task&lt;Stream&gt; dataStream = await GetPDF(document.DocumentPath)
  • @ArturLavrov 等待它将返回 Stream,而不是 Task&lt;Stream&gt;

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


【解决方案1】:

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

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    相关资源
    最近更新 更多