教程:为客户将 Power BI 内容嵌入应用中Tutorial: Embed Power BI content into an application for your customers

使用“Azure 中的 Power BI Embedded” ,可以借助“应用拥有数据”将报表、仪表板或磁贴嵌入到应用程序中。With Power BI Embedded in Azure, you can embed reports, dashboards, or tiles into an application using app owns data. 应用拥有数据是指将使用 Power BI 的应用程序作为其嵌入式分析平台。App owns data is about having an application that uses Power BI as its embedded analytics platform. ISV 开发者可以创建 Power BI 内容以便在完全集成并交互的应用程序中显示报表、仪表板或磁贴,用户无需 Power BI 许可证 。As an ISV developer, you can create Power BI content that displays reports, dashboards, or tiles in an application that is fully integrated and interactive, without requiring users to have a Power BI license. 本教程演示针对客户使用“Azure 中的 Power BI Embedded”时,如何使用 Power BI .NET SDK 以及 Power BI JavaScript API 将报表集成到应用程序中 。This tutorial demonstrates how to integrate a report into an application using the Power BI .NET SDK with the Power BI JavaScript API using Power BI Embedded in Azure for your customers.

Power BI 嵌入报表

在本教程中,了解如何:In this tutorial, you learn how to:

  • 在 Azure 中注册应用程序。Register an application in Azure.
  • 将 Power BI 报表嵌入到应用程序。Embed a Power BI report into an application.

先决条件Prerequisites

若要开始使用,则需要具有:To get started, you're required to have:

如果未注册 Power BI Pro ,请在开始之前注册以获得免费试用If you're not signed up for Power BI Pro, sign up for a free trial before you begin.

如果没有 Azure 订阅,请在开始之前先创建一个免费帐户If you don’t have an Azure subscription, create a free account before you begin.

设置嵌入式分析开发环境Set up your embedded analytics development environment

开始将报表、仪表板或磁贴嵌入应用前,需要先确保环境允许通过 Power BI 进行嵌入。Before you start embedding reports, dashboard, or tiles into your application, you need to make sure your environment allows for embedding with Power BI.

你可通过完成嵌入安装工具,快速开始并下载可帮助你逐步创建环境和嵌入报表的示例应用程序。You can go through the Embedding setup tool, so you can quickly get started and download a sample application that helps you walk through creating an environment and embedding a report.

但是,如果选择手动设置环境,则可以继续进行下面的操作。However, if you choose to set up the environment manually, you can continue below.

在 Azure Active Directory (Azure AD) 中注册应用程序Register an application in Azure Active Directory (Azure AD)

向 Azure Active Directory 注册应用程序,以允许应用程序访问 Power BI REST APIRegister your application with Azure Active Directory to allow your application access to the Power BI REST APIs. 通过注册应用,可以建立应用标识,并指定对 Power BI REST 资源的权限。Registering your application allows you to establish an identity for your application and specify permissions to Power BI REST resources. 根据你想要使用主帐户还是服务主体,确定如何开始注册应用程序。Depending if you want to use a master account or service principal, determines how to get started registering an application.

根据所采用的方法,影响 Azure 中注册的应用程序类型。Depending on which method you take, affects which type of application you register in Azure.

如果继续使用主帐户,则通过注册本机应用继续 。If you proceed using a master account, then proceed with registering a Native app. 由于使用非交互式登录,因此使用本机应用。You use a Native app because you're working with a non-interactive login.

但如果继续使用服务主体,则需要通过注册“服务器端 Web 应用程序”应用继续 。However, if you proceed using the service principal, you need to proceed with registering a server-side web application app. 注册服务器端 Web 应用程序以创建应用程序密码。You register a server-side web application to create an application secret.

设置 Power BI 环境Set up your Power BI environment

创建应用工作区Create an app workspace

如果为客户嵌入报表、仪表板或磁贴,则必须将内容放在应用工作区中。If you're embedding reports, dashboards, or tiles for your customers, then you have to place your content within an app workspace. 具有可以设置的不同类型工作区:传统工作区新工作区There are different types of workspaces that you can set up: the traditional workspaces or the new workspaces. 如果使用的是主帐户,则所用工作区类型并不重要 。If you're using a master account, then it doesn't matter which type of workspaces you use. 然而,如果使用服务主体登录应用程序,则需要使用新工作区 。However, if you use service principal to sign into your application, then you're required to you use the new workspaces. 在任一方案中,主帐户或服务主体必须是应用程序有关的应用工作区的管理员 。In either scenario, both the master account or service principal must be an admin of the app workspaces involved with your application.

创建并发布报表Create and publish your reports

可使用 Power BI Desktop 创建报表和数据集,然后将这些报表发布到应用工作区。You can create your reports and datasets using Power BI Desktop and then publish those reports to an app workspace. 可通过两种方式完成此任务:作为最终用户,可以使用主帐户(Power BI Pro 许可证)将报表发布到传统应用工作区。There are two ways to accomplish this task: As an end user, you can publish reports to a traditional app workspace with a master account (Power BI Pro license). 如果使用服务主体,则可以使用 Power BI REST API 将报表发布到新工作区。If you're using service principal, you can publish reports to the new workspaces using the Power BI REST APIs.

以下步骤介绍如何将 PBIX 报表发布到 Power BI 工作区。The below steps walk through how to publish your PBIX report to your Power BI workspace.

  1. 从 GitHub 下载示例博客演示Download the sample Blog Demo from GitHub.

    报表示例

  2. 在 Power BI Desktop 中打开示例 PBIX 报表 。Open sample PBIX report in Power BI Desktop.

    PBI Desktop 报表

  3. 发布到应用工作区 。Publish to app workspaces. 根据是否使用主帐户(Power Pro 许可证)或服务主体,此过程有所不同。This process differs depending on whether you're using a master account (Power Pro license), or service principal. 如果使用主帐户,则可以通过 Power BI Desktop 发布报表。If you're using a master account, then you can publish your report through Power BI Desktop. 现在,如果使用服务主体,则必须使用 Power BI REST API。Now if you're using service principal, you must use the Power BI REST APIs.

使用示例应用程序嵌入内容Embed content using the sample application

为了便于演示,故意采用简单的示例。This sample is deliberately kept simple for demonstration purposes. 应该由你或开发人员保护应用程序密码或主帐户凭据。It's up to the you or your developers to protect the application secret or the master account credentials.

请按照以下步骤,使用示例应用程序开始嵌入内容。Follow the steps below to start embedding your content using the sample application.

  1. 下载 Visual Studio(2013 版或更高版本)。Download Visual Studio (version 2013 or later). 请务必下载最新版 NuGet 包Make sure to download the latest NuGet package.

  2. 从 GitHub 下载应用拥有数据示例Download the App Owns Data sample from GitHub to get started.

    “应用拥有数据”应用程序示例

  3. 在示例应用程序中打开 Web.config 文件 。Open the Web.config file in the sample application. 必须填写以下字段,才能运行应用程序。There are fields you need to fill in to run the application. 可以对 AuthenticationType 选择 MasterUser 或 ServicePrincipal 。You can choose MasterUser or ServicePrincipal for the AuthenticationType. 你需要填充不同的字段,具体视选择的身份验证方法类型而定。Depending on which type of authentication method you choose there are different fields to complete.

    备注

    本示例中的默认 AuthenticationType 是 MasterUser 。The default AuthenticationType in this sample is MasterUser.

    MasterUserMasterUser
    (Power BI Pro 许可证)(Power BI Pro license)
    ServicePrincipalServicePrincipal
    (仅限应用的令牌)(app-only token)
    applicationIdapplicationId applicationIdapplicationId
    workspaceIdworkspaceId workspaceIdworkspaceId
    reportIdreportId reportIdreportId
    pbiUsernamepbiUsername
    pbiPasswordpbiPassword
    applicationsecretapplicationsecret
    tenanttenant

    Web 配置文件

应用程序 IDApplication ID

这两种 AuthenticationType(主帐户和服务主体)均需要此属性。This attribute is needed for both AuthenticationTypes (master account and service principal).

将 Azure 中的“应用 ID” 填入“applicationId” 字段。Fill in the applicationId information with the Application ID from Azure. 应用使用“applicationId” 对你向其请求获取权限的用户标识自身。The applicationId is used by the application to identify itself to the users from which you're requesting permissions.

若要获取“applicationId” ,请按以下步骤操作:To get the applicationId, follow these steps:

  1. 登录到 Azure 门户Sign into the Azure portal.

  2. 在左侧导航窗格中,依次选择“所有服务” 和“应用注册” 。In the left-hand navigation pane, select All Services, and select App Registrations.

    应用注册搜索

  3. 选择需要 applicationId 的应用程序 。Select the application that needs the applicationId.

    选择应用

  4. 存在列为 GUID 的“应用程序 ID” 。There's an Application ID that is listed as a GUID. 使用此“应用 ID” 作为应用的“applicationId” 。Use this Application ID as the applicationId for the application.

    applicationId

工作区 IDWorkspace ID

这两种 AuthenticationType(主帐户和服务主体)均需要此属性。This attribute is needed for both AuthenticationTypes (master account and service principal).

使用 Power BI 中的“应用工作区(组) GUID”填写“workspaceId”信息 。Fill in the workspaceId information with the app workspace (group) GUID from Power BI. 登录 Power BI 服务或使用 Powershell 时,可获得该信息。You can get this information either from the URL when signed into the Power BI service or using Powershell.

URLURL

workspaceId

PowerShellPowershell

Get-PowerBIworkspace -name "App Owns Embed Test"

powershell 中的 workspaceId

报表 IDReport ID

这两种 AuthenticationType(主帐户和服务主体)均需要此属性。This attribute is needed for both AuthenticationTypes (master account and service principal).

使用 Power BI 中的“报表 GUID”填写“reportId”信息 。Fill in the reportId information with the report GUID from Power BI. 登录 Power BI 服务或使用 Powershell 时,可获得该信息。You can get this information either from the URL when signed into the Power BI service or using Powershell.

URLURL

reportId

PowerShellPowershell

Get-PowerBIworkspace -name "App Owns Embed Test" | Get-PowerBIReport

powershell 中的 reportId

Power BI 用户名和密码Power BI username and password

仅主帐户 AuthenticationType 需要这些属性。These attributes are needed only for the master account AuthenticationType.

如果使用服务主体进行身份验证,则无需填写用户名或密码属性。If you're using service principal to authenticate, then you don't need to fill in the username or password attributes.

  • 使用 Power BI 主帐户填写“pbiUsername” 。Fill in the pbiUsername with the Power BI master account.
  • 使用 Power BI 主帐户的密码填写“pbiPassword” 。Fill in the pbiPassword with the password for the Power BI master account.

应用程序密码Application secret

服务主体 AuthenticationType 需要此属性。This attribute is needed only for the service principal AuthenticationType.

将 Azure 的“应用注册” 部分中的“密钥” 部分信息填入“ApplicationSecret” 字段。Fill in the ApplicationSecret information from the Keys section of your App registrations section in Azure. 使用服务主体时,此属性适用。This attribute works when using service principal.

若要获取“ApplicationSecret” ,请按以下步骤操作:To get the ApplicationSecret, follow these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 在左侧导航窗格中,依次选择“所有服务”和“应用注册” 。In the left-hand navigation pane, select All services and then select App registrations.

    应用注册搜索

  3. 选择需要使用“ApplicationSecret” 的应用。Select the application that needs to use the ApplicationSecret.

    选择一个应用

  4. 在“管理”下选择“证书和密码” 。Select Certificates and secrets under Manage.

  5. 选择“新的客户端密码” 。Select New client secrets.

  6. 在“说明”框中输入一个名称并选择持续时间。 Enter a name in the Description box and select a duration. 然后选择“保存”为应用程序获取“值”。 Then select Save to get the Value for your application. 如果在保存密钥值后关闭“密钥”窗格, 值字段会仅显示为隐藏状态。When you close the Keys pane after saving the key value, the value field shows only as hidden. 此时,你无法检索密钥值。At that point, you aren't able to retrieve the key value. 如果忘记了密钥值,请在 Azure 门户中新建密钥值。If you lose the key value, create a new one in the Azure portal.

    密钥值

租户Tenant

服务主体 AuthenticationType 需要此属性。This attribute is needed only for the service principal AuthenticationType.

使用 Azure 租户 ID 填写“租户”信息 。Fill in the tenant information with your azure tenant ID. 登录 Power BI 服务后通过 Azure AD 管理中心或使用 Powershell 可以获得该信息。You can get this information from the Azure AD admin center when signed into the Power BI service or by using Powershell.

运行应用程序Run the application

  1. 在“Visual Studio” 中选择“运行” 。Select Run in Visual Studio.

    运行应用程序

  2. 然后,选择“嵌入报表” 。Then select Embed Report. 根据你选择测试使用的内容(报表、仪表板或磁贴),在应用程序中选择该选项。Depending on which content you choose to test with - reports, dashboards or tiles - then select that option in the application.

    选择内容

  3. 现在,可以在示例应用程序查看报表。Now you can view the report in the sample application.

    查看应用程序

在应用程序中嵌入内容Embed content within your application

即使已使用 Power BI REST API 完成嵌入内容的步骤,也可使用 .NET SDK 编写本文中所述的示例代码 。Even though the steps to embed your content are done with the Power BI REST APIs, the example codes described in this article are made with the .NET SDK.

客户在应用程序中嵌入内容时,需要从 Azure AD 获取主帐户或服务主体的访问令牌 。Embedding for your customers within your application requires you to get an access token for your master account or service principal from Azure AD. 必须为 Power BI 应用程序获取 Azure AD 访问令牌,然后才能对 Power BI REST API 进行调用。You're required to get an Azure AD access token for your Power BI application before you make calls to the Power BI REST APIs.

若要使用访问令牌 创建 Power BI 客户端,不妨创建便于与 Power BI REST API 进行交互的 Power BI 客户端对象。To create the Power BI Client with your access token, you want to create your Power BI client object, which allows you to interact with the Power BI REST APIs. 使用 Microsoft.Rest.TokenCredentials 对象包装 AccessToken,以创建 Power BI 客户端对象。You create the 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. it's used to call 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 客户端对象检索对要嵌入的项的引用。You can use the Power BI client object to retrieve a reference to the item you want to embed.

下面的代码示例展示了如何从给定工作区检索首个报表。Here is a code sample of how to retrieve the first report from a given workspace.

示例应用程序的 Services\EmbedService.cs 文件中提供了获取内容项的示例,内容项包括报表、仪表板和希望嵌入的磁贴。 A sample of getting a content item whether it's a report, dashboard, or tile that you want to embed is available within the Services\EmbedService.cs file in the sample application.

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

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

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

创建嵌入令牌Create the embed token

生成了嵌入令牌,能够通过 JavaScript API 使用此令牌。Generated an embed token, which can be used from the JavaScript API. 嵌入令牌特定于要嵌入的项。The embed token is specific to the item you're embedding. 因此,只要嵌入 Power BI 内容,就需要为其新建嵌入令牌。So at any time you embed a piece of Power BI content, you need to create a new embed token for it. 有关详细信息(包括要使用哪个 accessLevel ),请参阅 GenerateToken APIFor more information, including which accessLevel to use, see GenerateToken API.

示例应用程序的 Services\EmbedService.cs 文件中提供了为报表、仪表板和希望嵌入的磁贴创建嵌入令牌的示例。 A sample of creating an embed token for a report, dashboard, or tile want to embed is available within the Services\EmbedService.cs file in the sample application.

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
};

为 EmbedConfig 和 TileEmbedConfig 创建了类。A class is created for EmbedConfig and TileEmbedConfig. Models\EmbedConfig.cs 文件和 Models\TileEmbedConfig.cs 文件中提供了示例。A sample is available within the Models\EmbedConfig.cs file and the Models\TileEmbedConfig.cs file.

使用 JavaScript 加载项Load an item using JavaScript

可以使用 JavaScript 将报表加载到网页上的 div 元素中。You can use JavaScript to load a report into a div element on your web page.

有关使用 JavaScript API 的完整示例,可以使用演练工具For a full sample of using the JavaScript API, you can use the Playground tool. 操场工具是演练不同类型的 Power BI Embedded 示例的快速方法。The Playground tool is a quick way to play with different types of Power BI Embedded samples. 还可以通过访问 PowerBI JavaScript wiki 页,获取有关 JavaScript API 的详细信息。You can also get more Information about the JavaScript API by visiting the PowerBI-JavaScript wiki page.

此示例对报表使用 EmbedConfig 模型和 TileEmbedConfig 模型及视图 。Here is a sample that uses an EmbedConfig model and a TileEmbedConfig model along with views for a report.

示例应用程序的 Views\Home\EmbedReport.cshtml、Views\Home\EmbedDashboard.cshtml 或 Views\Home\Embedtile.cshtml 文件中提供了为报表、仪表板或磁贴添加视图的示例 。A sample of adding a view for a report, dashboard, or tile is available within the Views\Home\EmbedReport.cshtml, Views\Home\EmbedDashboard.cshtml, or Views\Home\Embedtile.cshtml files in the sample application.

<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 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>

移动到生产环境Move to production

至此,你已完成应用程序的开发,接下来请回到应用工作区了解专用容量。Now that you've completed developing your application, it's time to back your app workspace with a dedicated capacity.

重要

移动到生产环境需要专用容量。Dedicated capacity is required to move to production.

创建专用容量Create a dedicated capacity

通过创建专用容量,可以利用好客户的专用资源。By creating a dedicated capacity, you can take advantage of having a dedicated resource for your customer. 可以在 Microsoft Azure 门户中购买专用容量。You can purchase a dedicated capacity within the Microsoft Azure portal. 有关如何创建 Power BI Embedded 容量的详细信息,请参阅在 Azure 门户中创建 Power BI Embedded 容量For details on how to create a Power BI Embedded capacity, see Create Power BI Embedded capacity in the Azure portal.

使用下表确定哪种 Power BI Embedded 容量最适合你的需求。Use the table below to determine which Power BI Embedded capacity best fits your needs.

容量节点Capacity Node 总核心数Total cores
(后端 + 前端) (Backend + frontend)
后端核心数Backend Cores 前端核心数Frontend Cores DirectQuery/实时连接限制DirectQuery/live connection limits
A1A1 1 个 V 核心1 v-core(s) 0.5 核、3GB RAM0.5 core(s), 3-GB RAM 0.5 核0.5 cores 每秒 0.5 个0 5 per second
A2A2 2 个 V 核心2 v-core(s) 1 核、5GB RAM1 core(s), 5-GB RAM 1 个核心1 cor(e) 每秒 10 个10 per second
A3A3 4 个 V 核心4 v-core(s) 2 核、10GB RAM2 core(s), 10-GB RAM 2 个核心2 core(s) 每秒 15 个15 per second
A4A4 8 个 V 核心8 v-core(s) 4 核、25GB RAM4 core(s), 25-GB RAM 4 个核心4 core(s) 每秒 30 个30 per second
A5A5 16 个 V 核心16 v-core(s) 8 核、50GB RAM8 core(s), 50-GB RAM 8 个核心8 core(s) 每秒 60 个60 per second
A6A6 32 个 V 核心32 v-core(s) 16 核、100GB RAM16 core(s), 100-GB RAM 16 个核心16 core(s) 每秒 120 个120 per second

使用 A SKU 时,无法使用免费的 Power BI 许可证访问 Power BI 内容。 With A SKUs, you can't access Power BI content with a FREE Power BI license.

使用 PRO 许可证的嵌入令牌仅用于开发测试,因此 Power BI 主帐户或服务主体可生成的嵌入令牌数量有限。Using embed tokens with PRO licenses are intended for development testing, so the number of embed tokens a Power BI master account or service principal can generate is limited. 必须具备专用容量才能嵌入到生产环境。A dedicated capacity requires embedding in a production environment. 为专用容量生成嵌入令牌时,可生成的数量不受限制。There's no limit on how many embed tokens you can generate with a dedicated capacity. 转到可用功能查看使用量值,该值以百分比表示当前嵌入使用量。Go to Available Features to check the usage value that indicates the current embedded usage in percentage. 使用量基于每个主帐户。The usage amount is based per master account.

有关详细信息,请参阅嵌入式分析容量规划白皮书For more information, see Embedded analytics capacity planning whitepaper.

为应用工作区分配专用容量Assign an app workspace to a dedicated capacity

创建专用容量后,可将该专用容量分配给应用工作区。Once you create a dedicated capacity, you can assign your app workspace to that dedicated capacity.

若要使用服务主体将专用容量分配给工作区,请使用 Power BI REST APITo assign a dedicated capacity to a workspace using service principal, use the Power BI REST API. 使用 Power BI REST API 时,请务必使用服务主体对象 IDWhen you are using the Power BI REST APIs, make sure to use the service principal object ID.

请按照以下步骤,使用主帐户将专用容量分配给工作区 。Follow the steps below to assign a dedicated capacity to a workspace using a master account.

  1. 在“Power BI 服务” 中,展开工作区并针对要嵌入内容的工作区选择相应省略号。Within the Power BI service, expand workspaces and select the ellipsis for the workspace you're using for embedding your content. 然后选择“编辑工作区” 。Then select Edit workspaces.

    编辑工作区

  2. 展开“高级”,启用“专用容量”,然后选择所创建的专用容量 。Expand Advanced, then enable Dedicated capacity, then select the dedicated capacity you created. 然后,选择“保存” 。Then select Save.

    分配专用容量

  3. 选择“保存” 后,应该会在应用工作区名称旁边看到一个钻石图形 。After you select Save, you should see a diamond next to the app workspace name.

    与容量绑定的应用工作区

后续步骤Next steps

在本教程中,你学习了如何将 Power BI 内容嵌入到客户的应用程序中。In this tutorial, you've learned how to embed Power BI content into an application for your customers. 你也可以尝试为组织嵌入 Power BI 内容。You can also try to embed Power BI content for your organization.

更多问题?More questions? 尝试咨询 Power BI 社区Try asking the Power BI Community