c# - HTTP 身份验证和 SQL Server 报告服务
问题描述
我正在尝试使用 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;
结果是“未经授权”。我错过了什么?
解决方案
您不需要使用基本身份验证来访问该 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。这是一个例子:
- 在 Project --> Add Service Reference -> Advanced -> Add Web Reference -> URL: http:////reportexecution2005.asmx 下并将其命名为 ReportExecution2005。
- 使用以下代码创建一个方法
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();
推荐阅读
- javascript - 集成以摄氏度转换开尔文的函数的问题
- javascript - 如何为 showSaveFilePicker 提供默认文件名
- wordpress - Wordpress Map Embed 添加 GestureHandling
- javascript - kitty img 的简单获取
- c# - 将 XPath 与 XDocument 一起使用时忽略 CData
- c - 在 shell 脚本中批量中止
- python - 在函数中使用 kwargs
- laravel - with() 中的回调在 laravel 雄辩的查询中返回 null
- javascript - 如何用数组解决javascript排序问题
- python - 对大列表的第一个字母进行排序和迭代