azure广告列表用户进入combobox图形api C#



我目前正在开发一个应用程序,需要从该公司的azure广告中获取所有用户

我设法做出选择,并让所有用户进入ResultText文本块。

我现在使用DisplayBasicTokenInfo((来填充一个文本框,但它只返回1个用户名,这是我自己的。现在我想做的是列出所有用户,并通过DisplayBasicTokenInfo将这些用户加载到一个组合框中。

我不知道这是否是最好的解决方案,但这就是我发现的。这样做的最终目标是,我希望每个Displayname都是一个comboboxItem

这是我目前掌握的代码。

public partial class TestGraphApi : Window
{
//Set the API Endpoint to Graph 'users' endpoint
string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/users?$select=displayName";
//Set the scope for API call to user.read.all
string[] _scopes = new string[] { "user.read.all" };
public TestGraphApi()
{
InitializeComponent();
}
/// <summary>
/// Call AcquireTokenAsync - to acquire a token requiring user to sign-in
/// </summary>
private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
{
AuthenticationResult authResult = null;
var app = App.PublicClientApp;
ResultText.Text = string.Empty;
TokenInfoText.Text = string.Empty;
var accounts = await app.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
try
{
authResult = await app.AcquireTokenSilent(_scopes, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilent.
// This indicates you need to call AcquireTokenInteractive to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
authResult = await app.AcquireTokenInteractive(_scopes)
.WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
}
catch (MsalException msalex)
{
ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
return;
}
if (authResult != null)
{
ResultText.Text = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);
DisplayBasicTokenInfo(authResult);
}
}
/// <summary>
/// Perform an HTTP GET request to a URL using an HTTP Authorization header
/// </summary>
/// <param name="url">The URL</param>
/// <param name="token">The token</param>
/// <returns>String containing the results of the GET operation</returns>
public async Task<string> GetHttpContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// Display basic information contained in the token
/// </summary>
private void DisplayBasicTokenInfo(AuthenticationResult authResult)
{
TokenInfoText.Text = "";
if (authResult != null)
{
TokenInfoText.Text += $"{authResult.Account.Username}";
}
}
}

您可以使用TokenInfoText.Text += $"{authResult.Account.Username}";在您的案例中设置TokenInfoText。

authResult.Account.Username只返回了用于获取访问令牌的登录用户,而没有返回API返回的用户。

如果你只想得到所有的displayNames,你可以解码ResultText.Text并得到值。将JSON字符串转换为JSON对象c#。

此外,您还可以使用Microsoft Graph SDK来获取用户。

private async Task<List<User>> GetUsersFromGraph()
{
// Create Graph Service Client, refer to https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret) 
.Build();
AuthorizationCodeProvider authenticationProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);
GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);
// Create a bucket to hold the users
List<User> users = new List<User>();
// Get the first page
IGraphServiceUsersCollectionPage usersPage = await graphServiceClient
.Users
.Request()
.Select(u => new {
u.DisplayName
})
.GetAsync();
// Add the first page of results to the user list
users.AddRange(usersPage.CurrentPage);
// Fetch each page and add those results to the list
while (usersPage.NextPageRequest != null)
{
usersPage = await usersPage.NextPageRequest.GetAsync();
users.AddRange(usersPage.CurrentPage);
}
return users;
}

最新更新