gpt4 book ai didi

azure - 在 ASP.Net Core 网站中嵌入 Power BI 报告

转载 作者:行者123 更新时间:2023-12-04 13:22:07 28 4
gpt4 key购买 nike

我有一个 ASP.Net core 1.1 网站,我想将 Power BI 报告嵌入到该网站中。

Azure 托管数据文档:https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-embed-sample-app-owns-data/

使用位于 https://github.com/Microsoft/PowerBI-Developer-Samples应用程序拥有的数据示例我有一个使用该示例的工作嵌入式报告解决方案。但是,示例项目正在 .Net Framework 4.5.2 上运行,当尝试将解决方案迁移到我的 .Net core 应用程序时,我已经迁移了代码,但是 .Net Core 中的 ActiveDirectorylibrary (Microsoft.IdentityModel.Clients.ActiveDirectorylibrary) 没有迁移包含 UserPasswordCredential 的方法

        var credential = new UserPasswordCredential(Username, Password);

我在网上找到的针对 ASP.Net core 推荐的解决方案是使用标签帮助程序,但是既然 Power BI Embedded 和 Power BI 服务已经与新推出的 Power BI Premium 融合,我认为这种解决方案是不可能的由于应用程序托管数据的 token 身份验证的依赖性。

完整报告 Controller 方法:

            public class ReportController : Controller
{
private static readonly string Username = ConfigurationManager.AppSettings["pbiUsername"];
private static readonly string Password = ConfigurationManager.AppSettings["pbiPassword"];
private static readonly string AuthorityUrl = ConfigurationManager.AppSettings["authorityUrl"];
private static readonly string ResourceUrl = ConfigurationManager.AppSettings["resourceUrl"];
private static readonly string ClientId = ConfigurationManager.AppSettings["clientId"];
private static readonly string ApiUrl = ConfigurationManager.AppSettings["apiUrl"];
private static readonly string GroupId = ConfigurationManager.AppSettings["groupId"];

public async Task<ActionResult> EmbedReport()
{
// 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, ClientId, credential);

if (authenticationResult == null)
{
return View(new EmbedConfig()
{
ErrorMessage = "Authentication Failed."
});
}

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

// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
// Get a list of reports.
var reports = await client.Reports.GetReportsInGroupAsync(GroupId);

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

if (report == null)
{
return View(new EmbedConfig()
{
ErrorMessage = "Group has no reports."
});
}

// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters);

if (tokenResponse == null)
{
return View(new EmbedConfig()
{
ErrorMessage = "Failed to generate embed token."
});
}

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

return View(embedConfig);
}
}
}

我尝试过:

在 .Net Core 项目中添加对 .Net Framework 4.6.1 的引用以公开 .Net Framework 并允许使用 IdentityModel.Clients.ActiveDirectory 的 .Net 等效项,但这似乎没有帮助。

如何解决 .Net core 中的库问题和嵌入问题?

编辑 - 答案

根据 @Fei Xu 提供的答案,我编写了一个 HTTP 帮助程序类,用于向 API 执行发布操作。根据返回的 JSON,我创建一个对象并使用现在可用的身份验证 token

帮助类:

  #region Settings

public static string BaseUrl
{
get
{
return "https://login.microsoftonline.com/common/oauth2/token";
}
}

#endregion

public static async Task<HttpResponseMessage> MakeAsyncRequest(string url, Dictionary<string, string> content)
{
var httpClient = new HttpClient
{
Timeout = new TimeSpan(0, 5, 0),
BaseAddress = new Uri(url)
};

httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");

if (content == null)
{
content = new Dictionary<string, string>();
}

var encodedContent = new FormUrlEncodedContent(content);

var result = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);

return result;
}

对象:

 public class AAD
{
public string token_type { get; set; }
public string scope { get; set; }
public string expires_in { get; set; }
public string ext_expires_in { get; set; }
public string expires_on { get; set; }
public string not_before { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
public string refresh_token { get; set; }
}

从 Controller 调用:

            var url = APIHelper.BaseUrl;
var content = new Dictionary<string, string>();
content["grant_type"] = "password";
content["resource"] = "https://analysis.windows.net/powerbi/api";
content["username"] = "<username>";
content["password"] = "<password>";
content["client_id"] = "<clientid>";

var response = await APIHelper.MakeAsyncRequest(url, content);
var result = response.Content.ReadAsStringAsync().Result;
var AAD = JsonConvert.DeserializeObject<AAD>(result);

最佳答案

Active Directory 身份验证库的 .Net core 不支持资源所有者密码凭据流程。

作为解决方法,您可以直接编写 HTTP 请求。下面是一个示例供您引用:

POST https://login.microsoftonline.com/{tenant}/oauth2/token 
Content-Type: application/x-www-form-urlencoded

grant_type=password
&resource={resource}
&username={username}
&password={password}
&client_id={clientid}
&client_secret={client_secret}//if it is confidential app

关于azure - 在 ASP.Net Core 网站中嵌入 Power BI 报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45480532/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com