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

Kca*_*evo 20 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)
  }
Run Code Online (Sandbox Code Playgroud)

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

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

Kir*_*lla 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);
    }
}
Run Code Online (Sandbox Code Playgroud)