Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NETMVC从外部API作为附件返回文件_C#_Asp.net Mvc - Fatal编程技术网

C# ASP.NETMVC从外部API作为附件返回文件

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

我有一个API端点,它将文件作为附件返回。例如,如果我访问www.myfileservice.com/api/files/download/123,我可以直接下载该文件。我的要求是在另一个ASP.NETMVC项目中使用此端点。因此,如果用户点击www.mymvcapapplication.com/File/DownloadDocument/123,也应该下载相同的文件。在内部,action方法应该调用文件服务API并按原样返回结果。这是我正在使用的代码:

FileController.cs:

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);
}
试试这个:这可能有帮助: