使用async Task <ihttpactionresult> </ihttpactionresult>的Web API 2下载文件

时间:2014-02-03 16:54:54

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

我需要编写如下方法来返回文本文档(.txt,pdf,.doc,.docx等) 虽然有很好的例子可以在Web上的Web API 2.0中发布文件,但我找不到只下载一个相关的文件。 (我知道如何在HttpResponseMessage中完成它。)

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

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

更重要的是在我以某种方式完成工作之前,我想知道做这种工作的“正确”方式是什么......(所以方法和技术提到非常感谢...祝贺。

2 个答案:

答案 0 :(得分:37)

是的,对于上面的方案,操作不需要返回异步操作结果。在这里,我正在创建一个自定义的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);
    }
}

答案 1 :(得分:3)

如果返回Task对象,则方法是异步的,而不是因为使用async关键字进行修饰。 async只是一种语法糖来代替这种语法,当有更多的任务组合或更多的延续时,它会变得相当复杂:

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

异步始终需要等待,这由编译器强制执行。

两种实现都是异步的,唯一的区别是async + await replaceces将ContinueWith扩展为&#34;同步&#34;代码。

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

所以问题的答案&#34;以上内容是否需要异步?我只想回流。 (可以吗?)&#34;它对调用者没有任何影响,只会改变代码的外观(但不会改变它的工作方式)。