IHttpActionResult>使用异步任务&LT网页API 2下载文件; [英] Web API 2 download file using async Task<IHttpActionResult>

查看:428
本文介绍了IHttpActionResult>使用异步任务&LT网页API 2下载文件;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个方法如下面返回一个文本文件(txt文件,PDF,.DOC,.DOCX等)
虽然有在网络上张贴的Web API 2.0文件的很好的例子,我找不到一个相关的一个只要下载之一。 (我知道该怎么做,在Htt的presponseMessage。)

I need to write a method like below to return a text document (.txt, pdf, .doc, .docx etc) While there are good examples of posting file in Web API 2.0 on the web , I couldn't find a relevant one for just downloading one. (I know how to do it in HttpResponseMessage.)

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

请问上述要求是异步呢?
我只希望返回流。 (这样行不行?)

Does the above needs to be async at all? I am only looking to return stream. (Is that okay?)

更重要的是之前,我最终会做这项工作的一种方式或otther,我想知道什么是做这种工作的正确的方式......(这样的方法和技术提这将大大AP preciated)..谢谢。

More importantly before I end up doing the job one way or the otther, I wanted to know what's the "right" way of doing this sort of job... (so approaches and techniques mentioning this would be greatly appreciated).. thanks.

推荐答案

右键,为您的上述方案的动作并不需要返回的异步的作用的结果。在这里,我创建一个自定义IHttpActionResult。您可以检查以下code在这里我的意见。

Right, for your above scenario the action does not need to return an async action result. Here I am creating a custom IHttpActionResult. You can check my comments in the below code here.

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);
    }
}

这篇关于IHttpActionResult&gt;使用异步任务&LT网页API 2下载文件;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆