分享方式:


教學課程:在組織的應用程式中內嵌Power BI報表

本教學課程說明如何在 .NET 5.0 應用程式中內嵌 Power BI 報表,做為組織內嵌的一部分(也稱為使用者擁有數據)解決方案的一部分在組織解決方案的內嵌中,您的應用程式用戶必須使用自己的認證向Power BI 進行驗證。

在本教學課程中,您將瞭解如何內嵌:

  • Power BI 報表
  • 在組織應用程式的內嵌中
  • 使用 .NET 5.0
  • 使用連結 Microsoft.Identity.Web 庫 (.NET Core 中也支援此連結庫)

注意

本教學課程中使用的完整解決方案可從 DOTNET5-UserOwnsData-Tutorial GitHub 存放庫取得。

必要條件

資源

在本教學課程中,您會使用:

方法

若要在組織解決方案的內嵌中內嵌Power BI內容,請遵循下列步驟:

  1. 設定您的 Microsoft Entra 應用程式
  2. 取得內嵌參數值
  3. 新增必要的 NuGet 套件
  4. 啟用伺服器端驗證
  5. 建置應用程式的用戶端
  6. 執行您的應用程式

步驟 1 - 設定您的 Microsoft Entra 應用程式

當您的 Web 應用程式呼叫 Power BI 時,它需要 Microsoft Entra 令牌 來呼叫 Power BI REST API,並內嵌 Power BI 專案,例如報表、儀錶板或磚。

如果您沒有 Microsoft Entra 應用程式,請使用註冊要與 Power BI 搭配使用的 Microsoft Entra 應用程式中的指示建立一個應用程式。

若要設定 Microsoft Entra 應用程式,請遵循設定 Microsoft Entra 應用程式中的指示。

步驟 2 - 取得內嵌參數值

若要內嵌報表,您需要下列值:

網域和租用戶標識碼

如果您不知道網域或租使用者標識符,請參閱 尋找 Microsoft Entra 租使用者標識碼和主要功能變數名稱

注意

若要 在不同的租 使用者(來賓使用者)上內嵌使用者的內容,您需要調整 authorityUri 參數。

Client ID

若要取得用戶端識別碼 GUID (也稱為 應用程式識別碼),請遵循下列步驟:

  1. 登入 Microsoft Azure

  2. 搜尋 應用程式註冊,然後選取 應用程式註冊 連結。

  3. 選取您用來內嵌 Power BI 內容的 Microsoft Entra 應用程式。

  4. 從 [概觀]段中,複製應用程式 (用戶端) 識別元 GUID。

用戶端密碼

若要取得客戶端密碼,請遵循下列步驟:

  1. 登入 Microsoft Azure

  2. 搜尋 應用程式註冊,然後選取 應用程式註冊 連結。

  3. 選取您用來內嵌 Power BI 內容的 Microsoft Entra 應用程式。

  4. 在 [管理] 下,選取 [憑證與秘密]。

  5. 在 [用戶端祕密] 下,選取 [新增用戶端祕密]

  6. 在 [ 新增客戶端密碼 ] 彈出視窗中,提供應用程式秘密的描述、選取應用程式秘密到期的時間,然後選取 [ 新增]。

  7. 從 [客戶端密碼] 區段中,複製新建立之應用程式秘密之 [值] 資料行中的字串。 用戶端密碼值是用戶端 識別碼

注意

請務必在客戶端密碼值第一次出現時複製它。 離開此頁面之後,客戶端密碼將會隱藏,您將無法擷取其值。

工作區識別碼

若要取得工作區標識碼 GUID,請遵循下列步驟:

  1. 登入 Power BI 服務。

  2. 開啟您想要內嵌的報表。

  3. 從 URL 複製 GUID。 GUID 是 /groups//reports/之間的數位。

    A screenshot showing workspace ID GUID in the Power B I service U R L

注意

若要以程序設計方式取得工作區標識符,請使用 取得群組 API。

報表標識碼

若要取得報表標識元 GUID,請遵循下列步驟:

  1. 登入 Power BI 服務。

  2. 開啟您想要內嵌的報表。

  3. 從 URL 複製 GUID。 GUID 是 /reports//ReportSection 之間的數位。

    A screenshot showing report ID GUID in the Power B I service U R L

注意

若要以程式設計方式取得報表標識碼,請使用 取得群組 API 中的報表。

步驟 3 - 新增必要的 NuGet 套件

開始之前,您需要將 、 和 Microsoft.PowerBI.Api NuGet 套件新增Microsoft.Identity.Web至您的應用程式。

將下列 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 程式代碼會完成數個重要事項:

  1. 的呼叫會設定 AddMicrosoftWebAppCallsWebApi Microsoft 驗證連結庫以取得存取令牌(Microsoft Entra 令牌)。
  2. 設定令牌快取的呼叫 AddInMemoryTokenCaches ,Microsoft 驗證連結庫將用來在幕後快取存取令牌和重新整理令牌
  3. 的呼叫 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 金鑰保存庫 來保留這項資訊。

  1. 在您的專案中,建立新的檔案並呼叫 appsettings.json

  2. 將下列程式代碼新增至 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": "*"
    }
    
  3. 填入從 步驟 2 - 取得內嵌參數值

注意

在先前的代碼段中,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 組態服務的實例,以用來從 appsettings.json 擷取組PowerBi:ServiceRootUrl態值。 名為 ITokenAcquisition 的參數會保存連結庫所Microsoft.Identity.Web提供之 Microsoft 驗證服務的參考,tokenAcquisition並用來從 Microsoft Entra ID 取得存取令牌。

欄位RequiredScopes會保存字串數位,其中包含一組由 Power BI 服務 API 支援的委派許可權。 當您的應用程式透過網路呼叫以取得 Microsoft Entra 令牌時,傳遞這組委派的許可權,讓 Microsoft Entra ID 可以將它們包含在它傳回的存取令牌中。

注意

確認您的 Microsoft Entra 應用程式 已設定 Web 應用程式所需的範圍。 如需詳細資訊,請參閱 變更 Microsoft Entra 應用程式的許可權

  1. 在應用程式的專案中,建立標題為 Services 的新資料夾。

  2. 在 [ 服務 ] 資料夾中,建立標題為 PowerBiServiceApi.cs 的新檔案。

  3. 將下列程式代碼新增至 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 檔案

在此程式代碼範例中,您會使用相依性插入。 當您在 方法中ConfigureServices呼叫 services.AddScopedPowerBiServiceApi將 類別註冊為服務時。 您可以將參數新增 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腳本。

  1. 在 [檢視>首頁] 資料夾中,建立名為Embed.cshtml的檔案。

  2. 將下列代碼段新增至 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,使用 組態物件來建立名為 embed.js 的 JavaScript 檔案,以內嵌報表。

models 是使用 對 window['powerbi-client'].models的呼叫初始化。 變數 models 是用來設定組態值,例如 models.Permissions.Allmodels.TokenType.Aadmodels.ViewMode.View

powerbi.embed 式會使用組 models 態物件來內嵌報表。

  1. wwwroot>js 資料夾中,建立名為 embed.js 的檔案。

  2. 將下列代碼段新增至 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 來增強您的應用程式。

當您的應用程式準備就緒時,您可以將 內嵌應用程式移至生產環境