Web API 2 download file using async Task

前端 未结 2 428
谎友^
谎友^ 2020-12-25 15:10

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

2条回答
  •  醉梦人生
    2020-12-25 15:25

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

提交回复
热议问题