1/22/2020 Admin
Embedding Power BI in Blazor
You can easily embed Power BI reports into a Server Side Blazor Application. This method allows you to display a Power BI report without requiring the user to have a Power BI account.
We start the code from the article: Embedded Power BI reports with ASP.NET Core by Gunnar Peipman.
His project demonstrates how to embed a Power BI report into a .Net Core application.
This example builds on that and shows you how to embed the report in a Server Side Blazor application.
Create The Project
The first step is to create a Server Side Blazor project and select Manage NuGet Packages.
Install the Microsoft.PowerBI.Api package.
The next step is to add the powerbi.min.js file to the wwwroot/js directory.
You can get that file from here: https://github.com/microsoft/PowerBI-JavaScript/releases
Next open the _Host.cshtml file.
Add the following code to reference the powerbi.min.js file:
<script src="js/powerbi.min.js"></script>
Add the following code to display the Power BI Report using the code in the powerbi.min.js file:
<script>window.ShowMyPowerBI = {
showReport: function (reportContainer, accessToken, embedUrl, embedReportId) {
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;var config = {
type: 'report',tokenType: models.TokenType.Embed,accessToken: accessToken,embedUrl: embedUrl,id: embedReportId,permissions: models.Permissions.All,settings: {filterPaneEnabled: true,
navContentPaneEnabled: true
}};// Embed the report and display it within the div container.
powerbi.embed(reportContainer, config);}};</script>
Next open the appsettings.json file and add the following configurations, replacing the {{ YOUR SETTING }} parts with your own settings. See Embedded Power BI reports with ASP.NET Core by Gunnar Peipman for an explanation of the settings and how to get them:
"PowerBI": {
"ApplicationId": "{{ YOUR SETTING }}","ApplicationSecret": "{{ YOUR SETTING }}","ReportId": "{{ YOUR SETTING }}","WorkspaceId": "{{ YOUR SETTING }}","AuthorityUrl": "{{ YOUR SETTING }}","ResourceUrl": "https://analysis.windows.net/powerbi/api","ApiUrl": "https://api.powerbi.com/","EmbedUrlBase": "https://app.powerbi.com/","UserName": "{{ YOUR SETTING }}","Password": "{{ YOUR SETTING }}"}
So that our C# code can communicate with the JavaScript, create a interop.cs file using the following code:
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Threading.Tasks;
namespace BlazorPowerBI
{public static class Interop{internal static ValueTask<object> CreateReport(IJSRuntime jsRuntime,ElementReference reportContainer,string accessToken,
string embedUrl,
string embedReportId)
{return jsRuntime.InvokeAsync<object>("ShowMyPowerBI.showReport",
reportContainer, accessToken, embedUrl,embedReportId);}}}
Finally, create a PowerBI.razor page using the following code:
@page "/PowerBI"
@using System.Net.Http
@using System.Threading.Tasks
@using Microsoft.AspNetCore.Mvc
@using Microsoft.PowerBI.Api.V2
@using Microsoft.PowerBI.Api.V2.Models
@using Microsoft.Rest
@using Newtonsoft.Json.Linq
@using Microsoft.Extensions.Configuration
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime@inject IConfiguration _configuration<div @ref="@PowerBIElement"style="height: 600px;width: 100%;max-width: 2000px;" />
@code {private ElementReference PowerBIElement;
protected override async TaskOnAfterRenderAsync(bool firstRender)
{if (firstRender)
{var accessToken = await GetPowerBIAccessToken();var tokenCredentials = new TokenCredentials(accessToken, "Bearer");using (var client = new PowerBIClient(new Uri(_configuration["PowerBI:ApiUrl"]), tokenCredentials)){var workspaceId = _configuration["PowerBI:WorkspaceId"];
var reportId = _configuration["PowerBI:ReportId"];
var report =await client.Reports.GetReportInGroupAsync(workspaceId, reportId);var generateTokenRequestParameters =new GenerateTokenRequest(accessLevel: "view");var tokenResponse = await client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);await Interop.CreateReport(JSRuntime,PowerBIElement,tokenResponse.Token,report.EmbedUrl,report.Id);}}}private async Task<string> GetPowerBIAccessToken(){using (var client = new HttpClient()){var form = new Dictionary<string, string>();form["grant_type"] = "password";form["resource"] = _configuration["PowerBI:ResourceUrl"];form["username"] = _configuration["PowerBI:UserName"];form["password"] = _configuration["PowerBI:Password"];form["client_id"] = _configuration["PowerBI:ApplicationId"];form["client_secret"] = _configuration["PowerBI:ApplicationSecret"];form["scope"] = "openid";client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");using (var formContent = new FormUrlEncodedContent(form))using (var response =
await client.PostAsync(_configuration["PowerBI:AuthorityUrl"],
formContent)){var body = await response.Content.ReadAsStringAsync();var jsonBody = JObject.Parse(body);var errorToken = jsonBody.SelectToken("error");
if (errorToken != null){throw new Exception(errorToken.Value<string>());}return jsonBody.SelectToken("access_token").Value<string>();}}}}
How It Works
The Gunnar Peipman version uses JQuery to connect the Power BI JavaScript to the HTML DIV to display the report.
This version literally passes an instance of the HTML DIV to the JavaScript to display the report.
This allows us to display the report without using JQuery.
Links
Embedded Power BI reports with ASP.NET Core
Gunnar Peipman – Programming Blog
gpeipman/AspNetCorePowerBI (GitHub)
Download
The project is available on the Downloads page on this site.
You must have Visual Studio 2019 Version 16.3 (or higher) installed to run the code.