我需要编写一种如下所示的方法来返回文本文档(.txt,pdf,.doc,.docx等),尽管在Web API 2.0中有很多在网络上发布文件的示例,但我找不到相关的示例仅下载一个。(我知道如何在HttpResponseMessage中执行此操作。)
public async Task<IHttpActionResult> 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<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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句