浏览器不是以PDF格式显示来自SSRS服务器的报告,而是显示来自Web服务器的原始响应

时间:2016-05-04 15:29:36

标签: c# asp.net http webclient ssrs-2012

以下是我用来以PDF格式显示来自SSRS服务器的报告的代码。

var reportServerUrl = new Uri(string.Format("{0}?{1}{2}&rs:aCommand=Render&rs:Format=pdf", 
            ConfigurationManager.AppSettings("ReportServerURL"), 
            ConfigurationManager.AppSettings("ReportFolder"), ItemPath));

var wcli = new WebClient();
wcli.Credentials = CustomReportCredentials.WebClientCredentials;
var fileBuffer = wcli.DownloadData(reportServerUrl);

if (fileBuffer != null)
{
   Response.ContentType = "application/pdf";
   Response.AddHeader("content-length", fileBuffer.Length.ToString());
   Response.BinaryWrite(fileBuffer);
}

它的大部分时间都有效。但是,有时当我点击链接时,我得到了一些奇怪的结果,而不是获取PDF格式的报告,这取决于浏览器。在CHROME中,我获取了页面的源代码。在IE中,我得到原始响应+一些stange字符(见图)。然后页面超时。

enter image description here

老实说,我不知道为什么会这样。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你看到有一个原始的二进制HTTP响应,包括标题和有效负载(这就是组成那些奇怪的字符)被解释为HTML。我认为您在此处缺少的是在设置标题后调用Response.Clear()

if (fileBuffer != null)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-length", fileBuffer.Length.ToString());
    Response.Clear();
    Response.BinaryWrite(fileBuffer);
}

如果不这样做,将保留网络服务器的默认标题。

话虽如此,我认为您并不需要设置有效负载的内容长度。请参阅Response.Flush()的示例。