轉自:http://space.itpub.net/9079672/viewspace-416169
WebForm下的ReportViewer控制項不能直接傳入身份憑證,因為其ServerReport.ReportServerCredentials.NetworkCredentials屬性是唯讀。
在騷擾了N個.NET MVP後,終於知道有一個介面叫IReportServerCredentials,誒,我怎麼把這茬忘了呢。報表格服務中定製化身分識別驗證方式的就靠它了。
既然是介面,那麼我們就要先利用這個介面建立一個類,然後類中實現這個介面的成員。IReportServerCredentials介面主要是兩個成員屬性(ImpersonateUser和NetworkCredentials)和一個成員方法(GetFormCredentials)。
ImpersonateUser在我們這兒沒什麼多大用處,哈,所以直接return null。NetworkCredentials就是我們需要返回的,所以return new NetworkCredential(_username, _password, _domain)。
那麼_username、_password、_domain哪兒來的呢,類裡面放三個Private的變數,然後通過類的初始化方法傳進去就行了啊。
這樣就搞定了阿。下面是類的原始碼和調用類的原始碼:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Web.SessionState;
using System.Security.Principal;
using System.Collections.Generic;
using Microsoft.Reporting.WebForms;
public partial class ReportViewer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
rptViewer.ProcessingMode = ProcessingMode.Remote;
rptViewer.ServerReport.ReportServerUrl = new Uri("http://Server Name/ReportServer");
rptViewer.ServerReport.ReportPath = "/Testing/EmployeeList";
ReportViewerCredentials.MyReportViewerCredential rvc=new ReportViewerCredentials.MyReportViewerCredential("user","password","");
rptViewer.ServerReport.ReportServerCredentials = rvc;
//new System.Net.NetworkCredential("reportuser", "userreport");
DataSourceCredentials dataSource = new DataSourceCredentials();
dataSource.Name="Data Source Name";
dataSource.UserId="UserID";
dataSource.Password="Password";
rptViewer.ServerReport.SetDataSourceCredentials(new DataSourceCredentials[] { dataSource });
List<ReportParameter> paramList = new List<ReportParameter>();
paramList.Add(new ReportParameter("Emp_No", " ", false));
paramList.Add(new ReportParameter("Birth_Date_From", "1980-01-01", false));
paramList.Add(new ReportParameter("Birth_Date_To", "1982-01-01", false));
this.rptViewer.ServerReport.SetParameters(paramList);
}
}
public class ReportViewerCredentials
{
public class MyReportViewerCredential : IReportServerCredentials
{
private string _username;
private string _password;
private string _domain;
public Uri ReportServerUrl;
public MyReportViewerCredential(string username, string password, string domain)
{
_username = username;
_password = password;
_domain = domain;
}
public WindowsIdentity ImpersonationUser
{
get { return null; }
}
public System.Net.ICredentials NetworkCredentials
{
get
{
return new NetworkCredential(_username, _password, _domain);
}
}
public bool GetFormsCredentials(out Cookie authCookie,
out string user,
out string password,
out string authority)
{
authCookie = null;
user = _username;
password = _password;
authority = _domain;
return false;
}
}
}