C# ASP.NETMVC从外部API作为附件返回文件
我有一个API端点,它将文件作为附件返回。例如,如果我访问www.myfileservice.com/api/files/download/123,我可以直接下载该文件。我的要求是在另一个ASP.NETMVC项目中使用此端点。因此,如果用户点击www.mymvcapapplication.com/File/DownloadDocument/123,也应该下载相同的文件。在内部,action方法应该调用文件服务API并按原样返回结果。这是我正在使用的代码: FileController.cs:C# ASP.NETMVC从外部API作为附件返回文件,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个API端点,它将文件作为附件返回。例如,如果我访问www.myfileservice.com/api/files/download/123,我可以直接下载该文件。我的要求是在另一个ASP.NETMVC项目中使用此端点。因此,如果用户点击www.mymvcapapplication.com/File/DownloadDocument/123,也应该下载相同的文件。在内部,action方法应该调用文件服务API并按原样返回结果。这是我正在使用的代码: FileController.cs: p
public HttpResponseMessage DownloadDocument(int Id)
{
return new DocumentClient().DownloadDocument(Id);
}
DocumentClient.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;
}
}
上面的代码没有给出任何错误,只是在浏览器窗口中打印响应(内容长度、内容配置等)。我需要下载文件。我认为最好是从控制器返回文件结果:
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);
}
试试这个:这可能有帮助: