Web API和报表查看器

时间:2014-10-26 04:46:51

标签: c# angularjs asp.net-web-api rdlc

我要求在Web API中生成一个服务,该服务将返回本地报表查看器文件的pdf。

在MVC中,您可以使用FileResult执行类似的操作,但我很难将其复制为HttpResponseMessage。有没有人试过或尝试做类似的事情?我尝试将byte []转换为流然后作为HttpResponse输出的所有尝试都以空文件结束。

public FileResult File() {
        // Create a new dataset
        StudentDataSet ds = new StudentDataSet();

        // Create and fill the Student data table
        // using the Student table adapter

        StudentDataSetTableAdapters.StudentTableAdapter dta =
               new StudentDataSetTableAdapters.StudentTableAdapter();
        dta.Fill(ds.Student);

        // Create a new report datasource with
        //      Name = the dataset name in the report,
        //      Value = the populated data table.

        ReportDataSource rds = new ReportDataSource();
        rds.Name = "DataSet1";
        rds.Value = ds.Student;

        ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
        rv.ProcessingMode = ProcessingMode.Local;
        rv.LocalReport.ReportPath = Server.MapPath("~/Reports/StudentReport.rdlc");

        // Add the new report datasource to the report.
        rv.LocalReport.DataSources.Add(rds);

        rv.LocalReport.Refresh();

        byte[] streamBytes = null;
        string mimeType = "";
        string encoding = "";
        string filenameExtension = "";
        string[] streamids = null;
        Warning[] warnings = null;

        streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);

        return File(streamBytes, mimeType, "StudentReport.pdf");
    }

2 个答案:

答案 0 :(得分:0)

请检查一下:How to return PDF to browser in MVC?

我没有看到您正在刷新流并将位置设置为0的任何位置。如果您的PDF文件为空,则需要将位置设置为0,以便数据具有字节流的起始位置。

答案 1 :(得分:0)

你可以试试这个..

                byte[] ResponseStream = objConnection.GetStream(letterNumber, paperType);
                HttpResponseMessage apiResponse;
                    apiResponse = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(ResponseStream)
                    };
                    apiResponse.Content.Headers.ContentLength = ResponseStream.Length;
                    apiResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    apiResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = String.Format("Letter_" + letterNumber + ".pdf")
                    };