C# 使用web api和angularjs下载excel文件

C# 使用web api和angularjs下载excel文件,c#,angularjs,asp.net-web-api,asp.net-web-api2,C#,Angularjs,Asp.net Web Api,Asp.net Web Api2,前端 var url = baseUrl+ "/api/Home/DownloadReport"; window.open(url); 后端 [HttpGet] public HttpResponseMessage DownloadReport() { var stream = new System.IO.MemoryStream(File.ReadAllBytes(@"C:\Users\mypc

前端

      var url = baseUrl+ "/api/Home/DownloadReport";
      window.open(url);
后端

     [HttpGet]

    public HttpResponseMessage DownloadReport()
    {
        var stream = new System.IO.MemoryStream(File.ReadAllBytes(@"C:\Users\mypc\Desktop\Test\5\WebApplication1\Report.xlsx"));
      HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream);
        };
        result.Content.Headers.ContentDisposition = new 
      System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "myworkbook.xlsx"
        };
        result.Content.Headers.ContentType = new 
        System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentLength = stream.Length;
        return result
         }
我正在尝试使用web API和angularjs下载excel文件,但当我单击“下载”按钮时,它会打开一个新选项卡,显示以下消息,但未下载该文件。是否有人可以向我建议代码的错误

状态代码:200,原因短语:'OK',版本:1.1,内容:System.Net.Http.ByteArrayContent,标题:{Content Type:application/octet-stream-Content-Disposition:attachment;filename=myworkbook.xlsx}

我知道以前有人问过这个问题,但尝试了许多解决方案,但未能解决问题

前端 不要使用
窗口。打开
,而是使用以下解决方法:

var url=baseUrl+“/api/Home/DownloadReport”;
var tmp=document.createElement('A');
tmp.href=url;
tmp.type='application/vnd.ms excel';
tmp.download='myworkbook.xlsx';
tmp.click();
后端
尝试在
MediaTypeHeaderValue
构造函数的参数中使用
application/vnd.ms excel

我尝试了上述建议的代码。但它显示了错误,例如myworkbook.xlsx的文件格式和扩展名不匹配。该文件可能已损坏或不安全。但服务器上的输入文件良好。我还尝试更改我的尝试了application/vnd.openxmlformat-officedocument.spreadsheetml.sheet,但尝试使用
StreamContent
而不是
ByteArrayContent
。谢谢。我通过将返回类型更改为filereturn解决了这个问题,现在它开始工作了