首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET ReportViewer 傳遞自訂憑證連線報表伺服器

     編輯:關於ASP.NET

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 認證
    }
}

步驟二:套用至 ReportViewer

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";
    }
}

補充說明

  • 帳號需具備報表伺服器的「瀏覽報表」權限。
  • 若報表伺服器啟用 HTTPS,確保伺服器憑證受信任,否則會發生 SSL 驗證失敗。
  • 生產環境建議將帳號密碼儲存於 Web.config <appSettings> 或 Azure Key Vault,避免硬編碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved