power bi 使用C# SKD获取Embed Token

在把power bi 的报表嵌入到Web的时候需要先获取Embed Token, 在这之前需要在Azure上创建应用程序,这个就不在这里说了,MSDN上有文档。 

下面直接上代码:

                // Create a user password cradentials.
                var credential = new UserPasswordCredential(Username, Password);
                // Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult = await             authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential);
                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                {
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);
                    if (reports.Value.Count() == 0)
                    {
                        result.ErrorMessage = "No reports were found in the workspace";
                        return result;
                    }
                    Microsoft.PowerBI.Api.V2.Models.Report report;
                    report = reports.Value.FirstOrDefault(r => r.Id.ToUpper().Equals(ReportId.ToUpper()));
                    if (report == null)
                    {
                        result.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid.";
                        return result;
                    }
                    var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);
                    result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
                    result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                    GenerateTokenRequest generateTokenRequestParameters;
                    if (result.IsEffectiveIdentityRequired == true)//当数据集有设置身份权限的时候 
                    {
                        if (!string.IsNullOrWhiteSpace(userAccount))
                        {       //Cube数据权限设置,当数据源为Cube的时候  2019年6月21日19:22:40  
                            var rls = new EffectiveIdentity(userAccount, new List<string> { report.DatasetId });
                            if (!string.IsNullOrWhiteSpace(userRole))
                            {   //当为报表数据权限控制行为是“RLS”行级安全性的时候,带入Role去生成嵌入的Token; 2019年6月21日19:23:47 
                                var rolesList = new List<string>();
                                rolesList.AddRange(userRole.Split(','));
                                rls.Roles = rolesList;
                            }
                            // Generate Embed Token with effective identities.
                            generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
                        }
                        else
                        {
                            // Generate Embed Token for reports without effective identities.
                            generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                        }
                    }
                    else
                    {
                        // Generate Embed Token for reports without effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    }
                    var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);
                    if (tokenResponse == null)
                    {
                        result.ErrorMessage = "Failed to generate embed token.";
                        return result;
                    }
                    result.EmbedToken = tokenResponse;
                    result.EmbedUrl = report.EmbedUrl;
                    result.Id = report.Id;
                    return result;
}

以上只是后端的代码,这个结果集返回到前端之后还有相应的代码。

<div id="reportContainer" style="height:99%;width:100%;margin-left:10px;margin-right:10px;"></div>
    // Read embed application token from Model
    /**/
    var accessToken = "@Model.EmbedToken.Token";
    /**/
    var reportStatus = "view"; //当前报表状态 view||edit
    // Read embed URL from Model
    var embedUrl = "@Model.EmbedUrl"



    // 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,
        background: models.BackgroundType.Transparent,
        //viewMode: models.ViewMode.Edit,
        settings: {
            filterPaneEnabled: false,
            navContentPaneEnabled: false
        }
    };

    // 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);

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值