使用异步任务的Web API 2下载文件

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

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

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

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

是的,对于上面的场景,操作不需要返回异步操作结果。 在这里,我正在创建一个自定义的IHttpActionResult。 您可以在此处查看以下代码中的评论。

 public IHttpActionResult GetFileAsync(int fileId) { // NOTE: If there was any other 'async' stuff here, then you would need to return // a Task, 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 ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StreamContent(File.OpenRead(@"" + 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); } } 

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

 public Task 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总是需要等待,这是由编译器强制执行的。

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

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

所以你的问题的答案是“上面的内容是否需要异步?我只想回流。(这样可以吗?)”是因为它对调用者没有任何影响,它只会改变代码的外观(但不是它如何工作)。