本教學課程說明如何在 .NET 5.0 應用程式中內嵌 Power BI 報表,做為「為您的組織內嵌」(也稱為「使用者擁有資料」) 解決方案的一部分。 在「為您的組織內嵌」解決方案中,您的應用程式使用者需要透過自己的認證針對 Power BI 進行驗證。
在本教學課程中,您會了解如何內嵌:
- Power BI 報表
- 在「為您的組織內嵌」應用程式中
- 使用 .NET 5.0
- 透過
Microsoft.Identity.Web程式庫 (.NET Core 中也支援此程式庫)
注意
本教學課程中使用的完整解決方案可從 DOTNET5-UserOwnsData-Tutorial GitHub 存放庫取得。
必要條件
Power BI Pro 或 Premium Per User (PPU) 授權。
注意
組織解決方案的內嵌不支援以 A SKU 為基礎的容量。 A SKU 只能用於為客戶解決方案的內嵌。
具有報表的 Power BI 工作區。
您自己的 Microsoft Entra 租戶。
.NET Core 5 模型檢視控制器 (MVC) 應用程式。
.NET Core 5 SDK (或更新版本)。
整合式開發環境 (IDE)。 建議您使用下列其中一個環境:
資源
在本教學課程中,您會使用:
- Power BI REST 報表 API - 嵌入 URL 並擷取嵌入令牌。
- Microsoft Identity Web 驗證連結庫。
- Power BI 內嵌分析用戶端 API - 內嵌報表。
方法
若要在「為您的組織內嵌」解決方案中內嵌 Power BI 內容,請遵循下列步驟:
步驟 1 - 設定您的 Microsoft Entra 應用程式
當您的 Web 應用程式呼叫 Power BI 時,它需要 Microsoft Entra 令牌 來呼叫 Power BI REST API,並內嵌 Power BI 專案,例如報表、儀錶板或磚。
如果您沒有 Microsoft Entra 應用程式,請使用 註冊Microsoft Entra 應用程式中的指示來建立一個搭配 Power BI 使用。
若要設定Microsoft Entra 應用程式,請遵循設定 Microsoft Entra 應用程式中的指示。
步驟 2 - 取得內嵌參數值
若要內嵌您的報表,您需要下列值:
網域和租用戶識別碼
如果您不知道您的網域或租用戶識別碼,請參閱 尋找 Microsoft Entra 租用戶識別碼和主要網域名稱。
注意
若要在不同的租戶中為來賓使用者內嵌內容,您需要調整authorityUri 參數。
用戶端識別碼
若要取得用戶端識別碼 GUID (也稱為 應用程式識別碼),請遵循下列步驟:
登入 Microsoft Azure。
搜尋 [應用程式註冊] ,然後選取 [ 應用程式註冊] 連結。
選取您用於內嵌 Power BI 內容的 Microsoft Entra 應用程式。
從 [概觀] 區段中,複製 [應用程式 (用戶端) 識別碼] GUID。
用戶端密碼
若要取得用戶端密碼,請遵循下列步驟:
登入 Microsoft Azure。
搜尋 [應用程式註冊] ,然後選取 [ 應用程式註冊] 連結。
選取您用於內嵌 Power BI 內容的 Microsoft Entra 應用程式。
在 [管理] 下,選取 [憑證和密碼]。
在 [用戶端祕密] 下,選取 [新增用戶端祕密]。
在 [新增用戶端祕密] 快顯視窗中,提供應用程式祕密的描述、選擇應用程式祕密何時到期,然後選取 [新增]。
從 [用戶端祕密] 區段中,複製新建立的應用程式祕密中 [值] 資料行的字串。 用戶端祕密值是您的「用戶端識別碼」。
注意
請務必在用戶端密碼值第一次出現時將其複製。 在瀏覽完此頁面之後,用戶端密碼便會隱藏,您將無法擷取其值。
工作區識別碼
若要取得工作區識別碼 GUID,請遵循下列步驟:
登入 Power BI 服務。
開啟您想要內嵌的報表。
複製 URL 中的 GUID。 GUID 是 /groups/ 和 /reports/之間的數位。
注意
若要以程序設計方式取得工作區標識符,請使用 取得群組 API。
報表識別碼
若要取得報表識別碼 GUID,請遵循下列步驟:
登入 Power BI 服務。
開啟您想要內嵌的報表。
複製 URL 中的 GUID。 GUID 是 /reports/ 和 /ReportSection 之間的數位。
注意
若要以程式設計方式取得報表標識碼,請使用 取得群組 API 中的報表 。
步驟 3 - 新增必要的 NuGet 套件
開始之前,您需要將 Microsoft.Identity.Web 和 Microsoft.PowerBI.Api NuGet 套件新增至您的應用程式。
將下列 NuGet 套件新增至您的應用程式:
在 VS Code 中,開啟終端機並輸入下列程式代碼。
在 Visual Studio 中,流覽至 [工具>][NuGet 套件管理員套件管理員>控制台 ],然後輸入下列程序代碼。
dotnet add package Microsoft.Identity.Web -v 0.3.0-preview
dotnet add package Microsoft.Identity.Web.UI -v 0.3.0-preview
dotnet add package Microsoft.PowerBI.Api
如果您的應用程式先前使用 Microsoft.AspNetCore 進行驗證,請輸入下列命令,從您的專案中移除此套件:
dotnet remove package Microsoft.AspNetCore.Authentication.AzureAD.UI
步驟 4 - 啟用伺服器端驗證
藉由建立或修改下表中的檔案,在您的應用程式中啟用伺服器端驗證。
| 檔案 | 使用 |
|---|---|
| Startup.cs | 初始化 Microsoft.Identity.Web 驗證服務 |
| appsettings.json | 驗證詳細資料 |
| PowerBiServiceApi.cs | 取得 Microsoft Entra 權杖和內嵌中繼資料 |
| HomeController.cs | 將內嵌資料以模型形式傳遞至檢視 |
設定您的啟動檔案以支援 Microsoft.Identity.Web
修改 Startup.cs 中的程式碼,以正確初始化 所提供的 Microsoft.Identity.Web驗證服務。
將下列代碼段新增至應用程式的 Startup.cs 檔案。
注意
ConfigureServices 中的程式碼會完成數個重要事項:
- 呼叫
AddMicrosoftWebAppCallsWebApi會設定 Microsoft 驗證程式庫,以取得存取權杖 (Microsoft Entra 權杖)。 - 呼叫
AddInMemoryTokenCaches會設定權杖快取,而 Microsoft 驗證程式庫將其用來快取存取權杖,並在幕後重新整理這些權杖 - 呼叫
services.AddScoped(typeof(PowerBiServiceApi))會將PowerBiServiceApi類別設定為服務類別,其可以使用相依性插入新增至其他類別。
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.TokenCacheProviders;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
using Microsoft.Identity.Web.UI;
using UserOwnsData.Services;
namespace UserOwnsData {
public class Startup {
public Startup (IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices (IServiceCollection services) {
services
.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(PowerBiServiceApi.RequiredScopes)
.AddInMemoryTokenCaches();
services.AddScoped (typeof (PowerBiServiceApi));
var mvcBuilder = services.AddControllersWithViews (options => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add (new AuthorizeFilter (policy));
});
mvcBuilder.AddMicrosoftIdentityUI();
services.AddRazorPages();
}
}
}
建立驗證詳細資料檔案
在本教學課程中,appsettings.json 檔案包含敏感性資訊,例如「用戶端識別碼」和「用戶端密碼」。 基於安全性原因,我們不建議將此資訊保留在設定檔中。 在應用程式中內嵌時,請考慮使用更安全的方法,例如 Azure Key Vault 來保留這項資訊。
在您的專案中,建立新的檔案,並將其 呼叫appsettings.json。
將下列程式代碼新增至 appsettings.json:
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "", "TenantId": "", "ClientId": "", "ClientSecret": "", "CallbackPath": "/signin-oidc", "SignedOutCallbackPath": "/signout-callback-oidc" }, "PowerBi": { "ServiceRootUrl": "https://api.powerbi.com" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
注意
在先前的程式碼片段中,PowerBi:ServiceRootUrl 參數會新增為自訂設定值,以追蹤 Power BI 服務的基礎 URL。 針對 Microsoft 公用雲端中的 Power BI 服務進行程式設計時,URL 是 https://api.powerbi.com/。 不過,Power BI 服務的根 URL 在其他雲端中會有所不同,例如政府雲端。 因此,此值會儲存為專案設定值,以便在需要時容易變更。
取得 Microsoft Entra 存取權杖,並呼叫 Power BI 服務
若要內嵌 Power BI 內容(例如報表和儀錶板),您的應用程式必須取得 Microsoft Entra 令牌。 若要取得令牌,您需要設定 物件。
本節中的程式碼會使用 .NET Core 相依性插入模式。 當您的類別需要使用服務時,您可以為該服務新增建構函式參數,而 .NET Core 執行階段會負責在執行階段傳遞服務執行個體。 在此情況下,建構函式會使用 IConfiguration 參數插入 .NET Core 組態服務的實例,用來從 PowerBi:ServiceRootUrl組態值。
ITokenAcquisition 參數 (名為 tokenAcquisition) 會保留對 Microsoft.Identity.Web 程式庫所提供 Microsoft 驗證服務的參考,並用來從 Microsoft Entra ID 取得存取權杖。
欄位 RequiredScopes 保存著字串陣列,其中包含 Power BI 服務 API 支援的一組 委派許可權 集合。 當您的應用程式透過網路呼叫以取得 Microsoft Entra 權杖時,請傳遞此委派權限集,以便 Microsoft Entra ID 可以將這些權限包含在其傳回的存取權杖中。
注意
驗證您的「Microsoft Entra 應用程式」是否已設定為具有 Web 應用程式所需的範圍。 如需詳細資訊,請參閱 變更Microsoft Entra 應用程式的許可權。
在應用程式的專案中,建立標題為 Services 的新資料夾。
在 [服務 ] 資料夾中,建立標題為 PowerBiServiceApi.cs的新檔案。
將下列程式代碼新增至 PowerBiServiceApi.cs。
using Microsoft.Identity.Web; using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using Newtonsoft.Json; namespace UserOwnsData.Services { // A view model class to pass the data needed to embed a single report. public class EmbeddedReportViewModel { public string Id; public string Name; public string EmbedUrl; public string Token; } public class PowerBiServiceApi { private ITokenAcquisition tokenAcquisition { get; } private string urlPowerBiServiceApiRoot { get; } public PowerBiServiceApi(IConfiguration configuration, ITokenAcquisition tokenAcquisition) { this.urlPowerBiServiceApiRoot = configuration["PowerBi:ServiceRootUrl"]; this.tokenAcquisition = tokenAcquisition; } public static readonly string[] RequiredScopes = new string[] { "https://analysis.windows.net/powerbi/api/Report.Read.All" }; // A method to get the Azure AD token (also known as 'access token') public string GetAccessToken() { return this.tokenAcquisition.GetAccessTokenForUserAsync(RequiredScopes).Result; } public PowerBIClient GetPowerBiClient() { var tokenCredentials = new TokenCredentials(GetAccessToken(), "Bearer"); return new PowerBIClient(new Uri(urlPowerBiServiceApiRoot), tokenCredentials); } public async Task<EmbeddedReportViewModel> GetReport(Guid WorkspaceId, Guid ReportId) { PowerBIClient pbiClient = GetPowerBiClient(); // Call the Power BI Service API to get embedding data var report = await pbiClient.Reports.GetReportInGroupAsync(WorkspaceId, ReportId); // Return report embedding data to caller return new EmbeddedReportViewModel { Id = report.Id.ToString(), EmbedUrl = report.EmbedUrl, Name = report.Name, Token = GetAccessToken() }; } } }
修改 HomeController.cs 檔案
在此程式碼範例中,您會使用相依性插入。 當您在 PowerBiServiceApi 方法中呼叫了 services.AddScoped,將 ConfigureServices 類別註冊為服務時, 您可以將 PowerBiServiceApi 參數新增至建構函式,而且 .NET Core 執行階段會負責建立 PowerBiServiceApi 執行個體,並將其傳遞至建構函式。
從 Controllers 資料夾開啟 HomeController.cs 檔案,並將它新增至下列代碼段:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using UserOwnsData.Models;
using UserOwnsData.Services;
namespace UserOwnsData.Controllers {
[Authorize]
public class HomeController : Controller {
private PowerBiServiceApi powerBiServiceApi;
public HomeController (PowerBiServiceApi powerBiServiceApi) {
this.powerBiServiceApi = powerBiServiceApi;
}
[AllowAnonymous]
public IActionResult Index() {
return View();
}
public async Task<IActionResult> Embed() {
Guid workspaceId = new Guid("11111111-1111-1111-1111-111111111111");
Guid reportId = new Guid("22222222-2222-2222-2222-222222222222");
var viewModel = await powerBiServiceApi.GetReport(workspaceId, reportId);
return View(viewModel);
}
[AllowAnonymous]
[ResponseCache (Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() {
return View (new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
步驟 5 - 建置應用程式的用戶端
針對用戶端實作,您需要建立或修改下表中的檔案。
| 檔案 | 使用 |
|---|---|
| embed.js | 包含用戶端 JavaScript 程式碼 |
| Embed.cshtml | 包含應用程式的文件物件模型 (DOM),以及用於內嵌報表的 DIV |
為內嵌的報表建立容器
建立 Embed.cshtml 檔案,其中包含用來作為內嵌報表容器的專案,以及三個 div 腳本。
在 [ 檢視>首頁 ] 資料夾中,建立名為 Embed.cshtml的檔案。
將下列代碼段新增至 Embed.cshtml 檔案。
@model UserOwnsData.Services.EmbeddedReportViewModel; <div id="embed-container" style="height:800px;"></div> @section Scripts { <!-- powerbi.min.js is the JavaScript file that loads the client-side Power BI JavaScript API library. Make sure that you're working with the latest library version. You can check the latest library available in https://cdnjs.com/libraries/powerbi-client --> <script src="https://cdn.jsdelivr.net/npm/powerbi-client@2.21.0/dist/powerbi.min.js"></script> <!-- This script creates a JavaScript object named viewModel which is accessible to the JavaScript code in embed.js. --> <script> var viewModel = { reportId: "@Model.Id", embedUrl: "@Model.EmbedUrl", token: "@Model.Token" }; </script> <!-- This script specifies the location of the embed.js file --> <script src="~/js/embed.js"></script> }
新增用戶端 JavaScript 以內嵌報表
若要內嵌 Power BI 內容,您必須建立一個設定物件。 若要深入瞭解如何建立組態物件,請參閱 內嵌報表。
在本節中,您會使用 變數來建立名為 models 的 JavaScript 檔案,並搭配組態物件來內嵌報表。
models 是使用對 window['powerbi-client'].models 的呼叫進行初始化。
models 變數用來設定 models.Permissions.All、models.TokenType.Aad 和 models.ViewMode.View 等設定值。
powerbi.embed 函式會使用 models 設定物件來內嵌您的報表。
在 wwwroot>js 資料夾中,建立名為 embed.js的檔案。
將下列代碼段新增至 embed.js 檔案。
$(function(){ // 1 - Get DOM object for div that is report container let reportContainer = document.getElementById("embed-container"); // 2 - Get report embedding data from view model let reportId = window.viewModel.reportId; let embedUrl = window.viewModel.embedUrl; let token = window.viewModel.token // 3 - Embed report using the Power BI JavaScript API. let models = window['powerbi-client'].models; let config = { type: 'report', id: reportId, embedUrl: embedUrl, accessToken: token, permissions: models.Permissions.All, tokenType: models.TokenType.Aad, viewMode: models.ViewMode.View, settings: { panes: { filters: { expanded: false, visible: true }, pageNavigation: { visible: false } } } }; // Embed the report and display it within the div container. let report = powerbi.embed(reportContainer, config); // 4 - Add logic to resize embed container on window resize event let heightBuffer = 12; let newHeight = $(window).height() - ($("header").height() + heightBuffer); $("#embed-container").height(newHeight); $(window).resize(function() { var newHeight = $(window).height() - ($("header").height() + heightBuffer); $("#embed-container").height(newHeight); }); });
步驟 6 - 執行您的應用程式
在完成了本教學課程中列出的所有調整之後,您就可以執行應用程式。 執行您的應用程式,並實驗 Power BI 報表的內嵌方式。 您可以使用 Power BI內嵌式分析用戶端 API ,使用用戶端 API 來增強您的應用程式。
當您的應用程式準備就緒時,您可以將 內嵌應用程式移至生產環境。