使用异步任务<IHttpActionResult>下载 Web API 2 文件



我需要写下类似下面的方法才能返回文本文档(.txt,pdf,.doc,.docx等)尽管在Web API 2.0上发布文件的示例很好,但我找不到仅下载一个相关文件。(我知道如何在httpresponsemessage中做到这一点。)

  public async Task<IHttpActionResult> GetFileAsync(int FileId)
  {    
       //just returning file part (no other logic needed)
  }

以上是否需要异步?我只是想返回流。(可以吗?)

更重要的是在我最终以一种方式或otther做这项工作之前,我想知道什么是做这种工作的"正确"方法...非常感谢)..谢谢

正确,对于您上述方案,操作不需要返回 async 操作结果。在这里,我正在创建一个自定义IHTTPACTIONRESULT。您可以在以下代码中查看我的评论。

public IHttpActionResult GetFileAsync(int fileId)
{
    // NOTE: If there was any other 'async' stuff here, then you would need to return
    // a Task<IHttpActionResult>, but for this simple case you need not.
    return new FileActionResult(fileId);
}
public class FileActionResult : IHttpActionResult
{
    public FileActionResult(int fileId)
    {
        this.FileId = fileId;
    }
    public int FileId { get; private set; }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = new HttpResponseMessage();
        response.Content = new StreamContent(File.OpenRead(@"<base path>" + FileId));
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        // NOTE: Here I am just setting the result on the Task and not really doing any async stuff. 
        // But let's say you do stuff like contacting a File hosting service to get the file, then you would do 'async' stuff here.
        return Task.FromResult(response);
    }
}

如果返回任务对象,方法是异步的,不是因为用异步关键字装饰。异步只是一种句法糖来替换此语法,当有更多任务组合或更多连续性时,会变得相当复杂的是:

public Task<int> ExampleMethodAsync()
{
    var httpClient = new HttpClient();
    var task = httpClient.GetStringAsync("http://msdn.microsoft.com")
        .ContinueWith(previousTask =>
        {
            ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.n";
            int exampleInt = previousTask.Result.Length;
            return exampleInt;
        });
    return task;
}

与异步的原始样本:http://msdn.microsoft.com/en-us/library/hh156513.aspx

异步总是需要等待,这是由编译器强制执行的。

这两个实现都是异步的,唯一的区别是异步 等待替代将继续扩展到"同步"代码中。

从控制器方法返回任务IO(我估计的99%的情况)很重要,因为在进行IO操作时,运行时可以暂停并重复使用请求线程以服务其他请求。这降低了耗尽线程池螺纹的机会。这是有关该主题的文章:http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4

因此,您的问题的答案"以上是否需要异步?我只是想返回流。(可以吗?)代码外观(但不是如何工作)。

最新更新