我有一个MVC / Web API应用程序,该应用程序调用第二个Web API服务以请求下载文件。
第一个服务充当一种代理,允许网站(使用AngularJS)请求文件。代理服务调用后端服务来请求文件,然后将文件传递回代理,再到浏览器。
简而言之:
网站对网站API的调用。网站API调用安全API。安全API将文件返回到网站API。网站API将文件返回到浏览器。
我有一个扩展IHttpActionResult的类,如下所示:
public class DocumentFileResponse: IHttpActionResult
{
public MemoryStream FileContents;
public string FileName;
public HttpRequestMessage HttpRequestMessage;
public HttpResponseMessage HttpResponseMessage;
public DocumentFileResponse(MemoryStream data, HttpRequestMessage request, string filename)
{
FileContents = data;
HttpRequestMessage = request;
FileName = filename;
}
public System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
{
HttpResponseMessage = HttpRequestMessage.CreateResponse(HttpStatusCode.OK);
HttpResponseMessage.Content = new StreamContent(FileContents);
//httpResponseMessage.Content = new FileContents(bookStuff.ToArray());
HttpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
HttpResponseMessage.Content.Headers.ContentDisposition.FileName = FileName;
HttpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return System.Threading.Tasks.Task.FromResult(HttpResponseMessage);
}
}
安全API具有以下方法:
public IHttpActionResult GetById(int id)
{
DocumentBL Logic = new DocumentBL();
Documents Document = Logic.GetDocumentById(id);
var dataBytes = File.ReadAllBytes(ConfigurationManager.AppSettings["DocumentPath"].ToString() + "/" + Document.UniqueID);
var dataStream = new MemoryStream(dataBytes);
return new DocumentFileResponse(dataStream, Request, Document.Filename);
}
这部分工作正常:如果我尝试使用具有适当请求的浏览器直接访问该服务,则可以毫无问题地下载文件。
我不确定如何在Website API中编写方法以发出请求并将文件返回到浏览器。这是到目前为止我可以管理的最接近的结果,但是我知道这行不通。没有人有任何想法或他们可以建议的链接吗?
public DocumentFileResponse GetFile(int id)
{
// Connection to HTTP Client
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
DocumentFileResponse document = null;
try
{
// List data response.
HttpResponseMessage response = client.GetAsync("api/Documents/" + id).Result; // Blocking call!
document = response.Content.ReadAsHttpResponseMessageAsync();
}
catch (Exception e)
{
document.FileName = e.Message;
}
return document;
}