ReportViewer 預設使用目前登入身分連線報表伺服器。若需指定特定帳號 (如服務帳號),需實作 IReportServerCredentials 介面。
using Microsoft.Reporting.WebForms;
using System.Net;
using System.Security.Principal;
public class CustomReportCredentials : IReportServerCredentials
{
private readonly string _userName, _password, _domain;
public CustomReportCredentials(string userName, string password, string domain)
{
_userName = userName; _password = password; _domain = domain;
}
public WindowsIdentity ImpersonationUser => null; // 不使用模擬
public ICredentials NetworkCredentials => new NetworkCredential(_userName, _password, _domain);
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
authCookie = null; user = password = authority = null; return false; // 不使用 Forms 認證
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string user = "reportUser", pwd = "P@ssw0rd", domain = "CORP";
ReportViewer1.ServerReport.ReportServerCredentials = new CustomReportCredentials(user, pwd, domain);
ReportViewer1.ServerReport.ReportServerUrl = new Uri("https://reportserver/ReportServer");
ReportViewer1.ServerReport.ReportPath = "/Sales/MonthlyReport";
}
}
Web.config <appSettings> 或 Azure Key Vault,避免硬編碼。