教程:将 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. 军事承包商 (DoDCON)Military Contractors (DoDCON)

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

  • Power BI for Germany 云Power BI for Germany cloud

  • Power BI for China 云Power 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 for Germany 云帐户Power BI for China 云帐户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 上“应用拥有数据”示例中使用的代码。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):

    备注

    GCC 帐户仅支持 P 和 EM 容量。GCC accounts only support P and EM capacities.

  1. 使用 GCCCloud.config 内容覆盖 Cloud.config 文件。Overwrite Cloud.config file with GCCCloud.config content.

  2. 在 Web.config 文件中更新 applicationId(本机应用 applicationId)、workspaceId、用户(你的主用户)和密码。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.net/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 文件中更新 applicationId(本机应用 applicationId)、workspaceId、用户(你的主用户)和密码。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.microsoftonlineS.net/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 文件中更新 applicationId(本机应用 applicationId)、workspaceId、用户(你的主用户)和密码。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.net/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 for Germany 云参数Power BI for Germany cloud parameters
  1. 使用 Power BI for Germany 云内容覆盖 Cloud.config 文件。Overwrite Cloud.config file with Power BI for Germany cloud content.

  2. 在 Web.config 文件中更新 applicationId(本机应用 applicationId)、workspaceId、用户(你的主用户)和密码。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 文件中添加 Power BI for Germany 云参数,如下所示。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 for China 云参数Power BI for China cloud parameters
  1. 使用 Power BI for China 云内容覆盖 Cloud.config 文件。Overwrite Cloud.config file with Power BI for China cloud content.

  2. 在 Web.config 文件中更新 applicationId(本机应用 applicationId)、workspaceId、用户(你的主用户)和密码。Update applicationId (Native app applicationId), workspaceId, the user (your master user), and password in Web.config file.

  3. 在 web.config 文件中添加 Power BI for China 云参数,如下所示。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 for Germany 云 - https://app.powerbi.de/appsPower BI for Germany cloud - https://app.powerbi.de/apps

  • Power BI for China 云 - 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 文件中更改 applicationId 。To 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. 有关详细信息,请参阅对用户进行身份验证并获取 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) - http://login.microsoftonline.usMilitary Contractors (DoDCON) - http://login.microsoftonline.us

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

  • Power BI for Germany 云 - https://login.microsoftonline.dePower BI for Germany cloud - https://login.microsoftonline.de

  • Power BI for China 云 - 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. 使用 Microsoft.Rest.TokenCredentials 对象包装 AccessToken,以创建你的 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.

为 EmbedConfig 和 TileEmbedConfig 创建了类。A class is created for EmbedConfig and TileEmbedConfig. Models\EmbedConfig.cs 和 Models\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 嵌入示例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