HTTP身份验证和SQL Server报告服务

时间:2020-08-24 15:12:21

标签: c# sql-server http .net-core reporting-services

我正在尝试使用C#(。Net Core控制台应用程序)将SQL Server Reporting Services报表导出为PDF。如果我将以下内容直接粘贴到浏览器URL栏中,则PDF已成功保存到“下载”文件夹:

https://MyServer:443/ReportServer?/MyReport&rs:Format=PDF&ReportParameter=Whatever

这是我用来尝试在C#中执行相同操作的代码:

HttpClient client = new HttpClient();

var byteArray = Encoding.ASCII.GetBytes("MyUsername:MyPassword");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(byteArray));

var result = await client.GetAsync("https://MyServer:443/ReportServer?/MyReport&rs:Format=PDF&ReportParameter=Whatever);

Console.WriteLine(result.StatusCode);

return result;

结果为“未经授权”。我想念什么?

1 个答案:

答案 0 :(得分:1)

您无需使用基本身份验证即可访问该URL,而应使用SSRS WebService的DefaultCredential

var theURL = "http://ReportServer/ReportServer_MYSERVER/Pages/ReportViewer.aspx?%2fPurchaseOrder&rs:Command=Render&OrderID=100&rs:ClearSession=true&rs:Format=PDF";

WebClient Client = new WebClient();
Client.UseDefaultCredentials = true;

byte[] myDataBuffer = Client.DownloadData(theURL);

您还可以使用 ReportExecution2005 Web服务下载PDF。这是一个示例:

https://docs.microsoft.com/en-us/dotnet/api/reportexecution2005.reportexecutionservice.render?redirectedfrom=MSDN&view=sqlserver-2016#ReportExecution2005_ReportExecutionService_Render_System_String_System_String_System_String__System_String__System_String__ReportExecution2005_Warning____System_String___ _

  1. 在项目下->添加服务参考->高级->添加Web参考-> URL:http:////reportexecution2005.asmx,并将其命名为ReportExecution2005。
  2. 使用以下代码创建方法
ReportExecutionService rsExec = new ReportExecutionService();
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Url = "http://<My Server Name>/<My Report Server Name>/reportexecution2005.asmx";

string historyID = null;
string reportPath = "/<My Folder Name>/<My SSRS Report Name>";
rsExec.LoadReport(reportPath, historyID);

GetProperteriesSample.ReportExecution2005.ParameterValue[] executionParams;
executionParams = new GetProperteriesSample.ReportExecution2005.ParameterValue[1];
executionParams[0] = new GetProperteriesSample.ReportExecution2005.ParameterValue();
executionParams[0].Name = "My Parameter Name";
executionParams[0].Value = "My Parameter Value";
new GetProperteriesSample.ReportExecution2005.ParameterValue();

rsExec.SetExecutionParameters(executionParams, "en-us");

string deviceInfo = null;
string extension;
string encoding;
string mimeType;
GetProperteriesSample.ReportExecution2005.Warning[] warnings = null;
string[] streamIDs = null;
string format = "PDF";

Byte[] results = rsExec.Render(format, deviceInfo, out extension, out mimeType, out encoding, out warnings, out streamIDs);
FileStream stream = File.OpenWrite("c:\\My Destination Folder Name>\\<My PDF Report Name>.pdf");
stream.Write(results, 0, results.Length);
stream.Close();