[英]ASP.Net MVC return file as attachment from external API
I have an API endpoint that returns file as attachment.我有一个 API 端点,它以附件形式返回文件。 for example if I access www.myfileservice.com/api/files/download/123 I could download the file directly.
例如,如果我访问 www.myfileservice.com/api/files/download/123 我可以直接下载文件。 My requirement is to use this endpoint in another ASP.Net MVC project.
我的要求是在另一个 ASP.Net MVC 项目中使用这个端点。 So if the user hits www.mymvcapplication.com/File/DownloadDocument/123 it should also download the same file.
因此,如果用户点击 www.mymvcapplication.com/File/DownloadDocument/123 它也应该下载相同的文件。 Internally the action method should call the file service API and return the result as it is.
在内部,action 方法应该调用文件服务 API 并按原样返回结果。 This is the code I am using:
这是我正在使用的代码:
FileController.cs:文件控制器.cs:
public HttpResponseMessage DownloadDocument(int Id)
{
return new DocumentClient().DownloadDocument(Id);
}
DocumentClient.cs:文档客户端.cs:
public class DocumentClient
{
private string documentServiceURL = string.Empty;
private static string downloadDocumentUri = "api/files/download/";
protected HttpClient documentClient = null;
public DocumentClient()
{
documentServiceURL = "www.myfileservice.com";
documentClient = new HttpClient();
documentClient.BaseAddress = new Uri(documentServiceURL);
}
public HttpResponseMessage DownloadDocument(int Id)
{
return documentClient.GetAsync(String.Format("{0}/{1}", downloadDocumentUri, Id)).Result;
}
}
The code above is not giving any error but only printing the response in browser window(Content-Length, Content-Disposition etc).上面的代码没有给出任何错误,只是在浏览器窗口中打印响应(Content-Length、Content-Disposition 等)。 I need to download the file instead.
我需要下载文件。
I think the best is to return a FileResult from your controller:我认为最好的方法是从您的 controller 返回一个 FileResult:
public FileResult DownloadDocument(int Id)
{
var document = new DocumentClient().DownloadDocument(Id);
//do the transformation here
//...
//I don't know what is your file's extension, please replace "application/zip" if
//needed
return File(finalResult, "application/zip", fileName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.