22

テキスト ドキュメント (.txt、pdf、.doc、.docx など) を返すには、以下のようなメソッドを記述する必要があります。 Web API 2.0 でファイルを投稿する良い例が Web にありますが、関連するものを見つけることができませんでした。ダウンロードするだけです。(私は HttpResponseMessage でそれを行う方法を知っています。)

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

上記はまったく非同期である必要がありますか? 私はストリームを返すことだけを考えています。(それは大丈夫ですか?)

さらに重要なことに、何らかの方法で仕事を終える前に、この種の仕事を行う「正しい」方法は何かを知りたかったのです...(したがって、これに言及するアプローチとテクニックは大歓迎です..ありがとう.

4

2 に答える 2

40

上記のシナリオでは、アクションは非同期アクションの結果を返す必要はありません。ここでは、カスタム 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);
    }
}
于 2014-02-06T17:06:22.560 に答える