教學課程:針對國家/地區雲端將 Power BI 內容內嵌到您的應用程式Tutorial: Embed a Power BI content into your application for national clouds

了解如何在國家/地區雲端的商務程序應用程式內內嵌分析內容。Learn how to embed analytical content within your business process applications for the national cloud. 您可以使用 Power BI .NET SDK 搭配 Power BI JavaScript API 將報表、儀表板或圖格內嵌至 Web 應用程式。You can use the Power BI .NET SDK with the Power BI JavaScript API to embed a report, dashboard, or tile, into your web applications.

Power BI 也支援國家/地區雲端Power BI also supports national clouds.

不同的國家/地區雲端是:The different national clouds are:

  • 美國政府社群雲端 (GCC)U.S. Government Community Cloud (GCC)

  • U. S. 政府社群雲端 High (GCC High)Government Community Cloud High (GCC High)

  • U. S. 軍事承包商 (DoDCON)Military Contractors (DoDCON)

  • U. S. 軍事 (DoD)Military (DoD)

  • 適用於德國雲端的 Power BIPower BI for Germany cloud

  • 適用於中國雲端的 Power BIPower BI for China cloud

內嵌的儀表板

若要開始使用此逐步解說,您需要一個 Power BI 帳戶。To get started with this walkthrough, you need a Power BI account. 如未設定帳戶,則可以根據政府或國家/地區的類型,選擇正確的國家/地區雲端。If you don't have an account set up, then depending on the type of government or country you can choose the right national cloud for you. 您可以註冊一個美國政府 Power BI 帳戶、一個適用於德國雲端的 Power BI 帳戶或一個適用於中國雲端的 Power BI 帳戶You can sign up for a U. S. government Power BI account, a Power BI for Germany cloud account or a Power BI for China cloud account.

注意

想要改為內嵌組織的內容嗎?Looking to embed a dashboard for your organization instead? 請參閱將儀表板整合到應用程式中See, Integrate a dashboard into an app for your organization.

若要將儀表板整合到 Web 應用程式,請使用 Power BI API 和 Azure Active Directory (AD) 授權 存取權杖,以取得儀表板。To integrate a dashboard into a web app, you use the Power BI API, and an Azure Active Directory (AD) authorization access token to get a dashboard. 然後,使用內嵌權杖載入儀表板。Then, you load the dashboard using an embed token. Power BI API 可讓您以程式設計方式存取特定的 Power BI 資源。The Power BI API provides programmatic access to specific Power BI resources. 如需詳細資訊,請參閱 Power BI REST API、[Power BI .NET SDK 與 Power BI JavaScript APIFor more information, see Power BI REST API, [Power BI .NET SDK, and the Power BI JavaScript API.

下載範例Download the sample

本文顯示 GitHub 上 App Owns Data 範例中所使用的程式碼。This article shows the code used in the App Owns Data sample on GitHub. 若要依照本逐步解說進行,您可以下載範例。To follow along with this walkthrough, you can download the sample.

「應用程式擁有資料」範例

  • 政府社群雲端 (GCC):Government Community Cloud (GCC):

    注意

    您只能使用 Microsoft 365 SKU 從政府社群雲端 (GCC) 內嵌 Power BI 內容。Embedding Power BI content from a Government Community Cloud (GCC), can only be done with a Microsoft 365 SKU. 其他國家/地區的雲端客戶可使用 Microsoft 365 或 Azure SKUOther national cloud customers can use Microsoft 365 or Azure SKUs.

  1. 以 GCCCloud.config 內容覆寫 Cloud.config 檔案。Overwrite Cloud.config file with GCCCloud.config content.

  2. 更新 Web.config 檔案中的應用程式識別碼 (原生應用程式的應用程式識別碼)、工作區識別碼、使用者 (您的主要使用者) 與密碼。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 中新增 GCC 參數,如下所示。Add the GCC parameters in the web.config file as follows.

<add key="authorityUrl" value="https://login.microsoftonline.com/common/" />
<add key="resourceUrl" value="https://analysis.usgovcloudapi.net/powerbi/api" />
<add key="apiUrl" value="https://api.powerbigov.us/" />
<add key="embedUrlBase" value="https://app.powerbigov.us" />
  • 軍事承包商 (DoDCON):Military Contractors (DoDCON):
  1. 以 TBCloud.config 內容覆寫 Cloud.config 檔案。Overwrite Cloud.config file with TBCloud.config content.

  2. 更新 Web.config 檔案中的應用程式識別碼 (原生應用程式的應用程式識別碼)、工作區識別碼、使用者 (您的主要使用者) 與密碼。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 中新增 DoDCON 參數,如下所示。Add the DoDCON parameters in the web.config file as follows.

<add key="authorityUrl" value="https://login.microsoftonline.us/common/" />
<add key="resourceUrl" value="https://high.analysis.usgovcloudapi.net/powerbi/api" />
<add key="apiUrl" value="https://api.high.powerbigov.us/" />
<add key="embedUrlBase" value="https://app.high.powerbigov.us" />
  • 軍事 (DoD):Military (DoD):
  1. 以 PFCloud.config 內容覆寫 Cloud.config 檔案。Overwrite Cloud.config file with PFCloud.config content.

  2. 更新 Web.config 檔案中的應用程式識別碼 (原生應用程式的應用程式識別碼)、工作區識別碼、使用者 (您的主要使用者) 與密碼。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 中新增 DoDCON 參數,如下所示。Add the DoDCON parameters in the web.config file as follows.

<add key="authorityUrl" value="https://login.microsoftonline.us/common/" />
<add key="resourceUrl" value="https://mil.analysis.usgovcloudapi.net/powerbi/api" />
<add key="apiUrl" value="https://api.mil.powerbigov.us/" />
<add key="embedUrlBase" value="https://app.mil.powerbigov.us" />
  • 適用於德國雲端的 Power BI 參數Power BI for Germany cloud parameters
  1. 使用適用於德國雲端的 Power BI 內容覆寫 Cloud.config 檔案。Overwrite Cloud.config file with Power BI for Germany cloud content.

  2. 更新 Web.config 檔案中的應用程式識別碼 (原生應用程式的應用程式識別碼)、工作區識別碼、使用者 (您的主要使用者) 與密碼。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 檔案中新增適用於德國雲端的 Power BI 參數,如下所示。Add the Power BI for Germany cloud parameters in the web.config file as follows.

<add key="authorityUrl" value="https://login.microsoftonline.de/common/" />
<add key="resourceUrl" value="https://analysis.cloudapi.de/powerbi/api" />
<add key="apiUrl" value="https://api.powerbi.de/" />
<add key="embedUrlBase" value="https://app.powerbi.de" />
  • 適用於中國雲端的 Power BI 參數Power BI for China cloud parameters
  1. 使用適用於中國雲端的 Power BI 內容覆寫 Cloud.config 檔案。Overwrite Cloud.config file with Power BI for China cloud content.

  2. 更新 Web.config 檔案中的應用程式識別碼 (原生應用程式的應用程式識別碼)、工作區識別碼、使用者 (您的主要使用者) 與密碼。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 檔案中新增適用於中國雲端的 Power BI 參數,如下所示。Add the Power BI for China cloud parameters in the web.config file as follows.

<add key="authorityUrl" value="https://login.chinacloudapi.cn/common/" />
<add key="resourceUrl" value="https://analysis.chinacloudapi.cn/powerbi/api" />
<add key="apiUrl" value="https://api.powerbi.cn/" />
<add key="embedUrlBase" value="https://app.powerbi.cn" />

步驟 1 - 在 Azure AD 中註冊應用程式Step 1 - register an app in Azure AD

在 Azure AD 中註冊應用程式以進行 REST API 呼叫。Register your application with Azure AD to make REST API calls. 如需詳細資訊,請參閱註冊 Azure AD 應用程式以內嵌 Power BI 內容For more information, see Register an Azure AD app to embed Power BI content. 因為有不同的國家/地區雲端聯盟,所以註冊應用程式的 URL 不同。Since there are different national cloud affiliations, there are distinct URLs to register your application.

  • 政府社群雲端 (GCC): https://app.powerbigov.us/appsGovernment Community Cloud (GCC) - https://app.powerbigov.us/apps

  • 軍事承包商 (DoDCON): https://app.high.powerbigov.us/appsMilitary Contractors (DoDCON) - https://app.high.powerbigov.us/apps

  • 軍事 (DoD): https://app.mil.powerbigov.us/appsMilitary (DoD) - https://app.mil.powerbigov.us/apps

  • 適用於德國雲端的 Power BI: https://app.powerbi.de/appsPower BI for Germany cloud - https://app.powerbi.de/apps

  • 適用於中國雲端的 Power BI - https://app.powerbi.cn/appsPower BI for China cloud - https://app.powerbi.cn/apps

若您已經下載 對客戶進行內嵌範例,就能使用取得的 applicationId 來設定範例,以向 Azure AD 驗證。If you downloaded the Embedding for your customer sample, you would use the applicationId you get, so that the sample can authenticate to Azure AD. 若要設定範例,請變更 web.config 檔案中的 applicationIdTo configure the sample, change the applicationId in the web.config file.

步驟 2 - 從 Azure AD 取得存取權杖Step 2 - get an access token from Azure AD

在您的應用程式中,您必須從 Azure AD 取得 存取權杖,才能呼叫 Power BI REST API。Within your application, you need to get an access token, from Azure AD, before you can make calls to the Power BI REST API. 如需詳細資訊,請參閱 Authenticate users and get an Azure AD access token for your Power BI app (驗證使用者,並為 Power BI 應用程式取得 Azure AD 存取權杖)。For more information, see Authenticate users and get an Azure AD access token for your Power BI app. 因為有不同的國家/地區雲端聯盟,所以取得應用程式存取權杖的 URL 不同。Since there are different national cloud affiliations, there are distinct URLs to get an access token for your application.

  • 政府社群雲端 (GCC): https://login.microsoftonline.comGovernment Community Cloud (GCC) - https://login.microsoftonline.com

  • 軍事承包商 (DoDCON): https://login.microsoftonline.usMilitary Contractors (DoDCON) - https://login.microsoftonline.us

  • 軍事 (DoD): https://login.microsoftonline.usMilitary (DoD) - https://login.microsoftonline.us

  • 適用於德國雲端的 Power BI: https://login.microsoftonline.dePower BI for Germany cloud - https://login.microsoftonline.de

  • 適用於中國雲端的 Power BI - https://login.chinacloudapi.cnPower BI for China cloud - https://login.chinacloudapi.cn

您可以在 Controllers\HomeController.cs 檔案的每個內容項目工作中看到這些存取權杖範例。You can see examples of these access tokens within each content item task in the Controllers\HomeController.cs file.

步驟 3 - 取得內容項目Step 3 - get a content item

若要內嵌 Power BI 內容,您需要執行幾項工作以確保能夠正確地將其內嵌。To embed your Power BI content, you need to do a couple of things to make sure it embeds correctly. 雖然這些步驟全都能直接利用 REST API 完成,但這裡的範例應用程式及範例會使用 .NET SDK。While all of these steps can be done with the REST API directly, the sample application and the examples here use the .NET SDK.

使用存取權杖建立 Power BI 用戶端Create the Power BI Client with your access token

使用存取權杖,您需要建立 Power BI 用戶端物件,以便與 Power BI API 互動。With your access token, you want to create your Power BI client object, which allows you to interact with the Power BI APIs. 你可以將 AccessToken 與 Microsoft.Rest.TokenCredentials 物件包裝在一起來建立 Power BI 用戶端物件。You create your Power BI client object by wrapping the AccessToken with a Microsoft.Rest.TokenCredentials object.

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.PowerBI.Api.V2;

var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

// Create a Power BI Client object. This is used to call the Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
    // Your code to embed items.
}

取得您想要內嵌的內容項目Get the content item you want to embed

使用 Power BI 用戶端物件,擷取您想要內嵌之項目的參考。Use the Power BI client object to retrieve a reference to the item you want to embed. 您可以內嵌儀表板、圖格或報表。You can embed dashboards, tiles, or reports. 以下範例會示範如何從提供的工作區中擷取第一個儀表板、圖格或報表。Here is an example of how to retrieve the first dashboard, tile, or report from a given workspace.

您可以在 「應用程式擁有資料」範例Controllers\HomeController.cs 中找到範例。A sample is available within Controllers\HomeController.cs of the App Owns Data sample.

報表Reports

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// You need to provide the workspaceId where the dashboard resides.
ODataResponseListReport reports = client.Reports.GetReportsInGroupAsync(workspaceId);

// Get the first report in the group.
Report report = reports.Value.FirstOrDefault();

儀表板Dashboards

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// You need to provide the workspaceId where the dashboard resides.
ODataResponseListDashboard dashboards = client.Dashboards.GetDashboardsInGroup(workspaceId);

// Get the first report in the group.
Dashboard dashboard = dashboards.Value.FirstOrDefault();

Tiles

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// To retrieve the tile, you first need to retrieve the dashboard.

// You need to provide the workspaceId where the dashboard resides.
ODataResponseListDashboard dashboards = client.Dashboards.GetDashboardsInGroup(workspaceId);

// Get the first report in the group.
Dashboard dashboard = dashboards.Value.FirstOrDefault();

// Get a list of tiles from a specific dashboard
ODataResponseListTile tiles = client.Dashboards.GetTilesInGroup(workspaceId, dashboard.Id);

// Get the first tile in the group.
Tile tile = tiles.Value.FirstOrDefault();

建立內嵌權杖Create the embed token

使用 JavaScript API,您就可以產生內嵌權杖。Using the JavaScript API, you can generate an embed token. 內嵌權杖專屬於您內嵌的項目。The embed token is specific to the item you're embedding. 每次您內嵌 Power BI 內容時,都必須為其建立一個新的內嵌權杖。Anytime you embed a piece of Power BI content, you need to create a new embed token for it. 如需詳細資訊,包括要使用的 accessLevel,請參閱 Embed Token (內嵌權杖)。For more information, including which accessLevel to use, see Embed Token.

重要

因為內嵌權杖只適用於開發人員測試,所以 Power BI 主要帳戶可以產生的內嵌權杖數目有限。Because embed tokens are intended for developer testing only, the number of embed tokens a Power BI master account can generate is limited. 必須購買容量才可進行生產環境內嵌案例。A capacity must be purchased for production embedding scenarios. 購買容量後,內嵌權杖產生的數量就不受限制。There is no limit to embed token generation when a capacity is purchased.

您可以在 對組織進行內嵌範例Controllers\HomeController.cs 中找到範例。A sample is available within Controllers\HomeController.cs of the Embedding for your organization sample.

這會針對 EmbedConfigTileEmbedConfig 建立類別。A class is created for EmbedConfig and TileEmbedConfig. 您可以在 Models\EmbedConfig.csModels\TileEmbedConfig.cs 中找到範例。A sample is available within Models\EmbedConfig.cs and Models\TileEmbedConfig.cs.

報表Reports

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Reports.GenerateTokenInGroup(workspaceId, report.Id, generateTokenRequestParameters);

// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
    EmbedToken = tokenResponse,
    EmbedUrl = report.EmbedUrl,
    Id = report.Id
};

儀表板Dashboards

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Dashboards.GenerateTokenInGroup(workspaceId, dashboard.Id, generateTokenRequestParameters);

// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
    EmbedToken = tokenResponse,
    EmbedUrl = dashboard.EmbedUrl,
    Id = dashboard.Id
};

Tiles

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// Generate Embed Token for a tile.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Tiles.GenerateTokenInGroup(workspaceId, dashboard.Id, tile.Id, generateTokenRequestParameters);

// Generate Embed Configuration.
var embedConfig = new TileEmbedConfig()
{
    EmbedToken = tokenResponse,
    EmbedUrl = tile.EmbedUrl,
    Id = tile.Id,
    dashboardId = dashboard.Id
};

步驟 4 - 使用 JavaScript 載入項目Step 4 - load an item using JavaScript

您可以使用 JavaScript 將儀表板載入到網頁上的 div 項目中。You can use JavaScript to load a dashboard into a div element on your web page. 此範例會使用 EmbedConfig/TileEmbedConfig 模型,以及儀表板、圖格或報表的檢視。The sample uses an EmbedConfig/TileEmbedConfig model along with views for a dashboard, tile, or report. 如需使用 JavaScript API 的完整範例,您可以使用 Microsoft Power BI Embedded Sample (Microsoft Power BI 內嵌範例)。For a full sample of using the JavaScript API, you can use the Microsoft Power BI Embedded Sample.

您可以在對組織進行內嵌範例中找到應用程式範例。An application sample is available within the Embedding for your organization sample.

Views\Home\EmbedDashboard.cshtmlViews\Home\EmbedDashboard.cshtml

<script src="~/scripts/powerbi.js"></script>
<div id="dashboardContainer"></div>
<script>
    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read dashboard Id from Model
    var embedDashboardId = "@Model.Id";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'dashboard',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedDashboardId
    };

    // Get a reference to the embedded dashboard HTML element
    var dashboardContainer = $('#dashboardContainer')[0];

    // Embed the dashboard and display it within the div container.
    var dashboard = powerbi.embed(dashboardContainer, config);
</script>

Views\Home\EmbedTile.cshtmlViews\Home\EmbedTile.cshtml

<script src="~/scripts/powerbi.js"></script>
<div id="tileContainer"></div>
<script>
    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read tile Id from Model
    var embedTileId = "@Model.Id";

    // Read dashboard Id from Model
    var embedDashboardId = "@Model.dashboardId";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'tile',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedTileId,
        dashboardId: embedDashboardId
    };

    // Get a reference to the embedded tile HTML element
    var tileContainer = $('#tileContainer')[0];

    // Embed the tile and display it within the div container.
    var tile = powerbi.embed(tileContainer, config);
</script>

Views\Home\EmbedReport.cshtmlViews\Home\EmbedReport.cshtml

<script src="~/scripts/powerbi.js"></script>
<div id="reportContainer"></div>
<script>
    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read report Id from Model
    var embedReportId = "@Model.Id";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedReportId,
        permissions: models.Permissions.All,
        settings: {
            filterPaneEnabled: true,
            navContentPaneEnabled: true
        }
    };

    // Get a reference to the embedded report HTML element
    var reportContainer = $('#reportContainer')[0];

    // Embed the report and display it within the div container.
    var report = powerbi.embed(reportContainer, config);
</script>

後續步驟Next steps

考量與限制Considerations and limitations

有其他問題嗎?More questions? 嘗試在 Power BI 社群提問Try asking the Power BI Community