我想使用userPrincipleName或对象ID获取用户详细信息.

我试过了,但他们给了我下面提到的错误.

The expression cannot be evaluated.A common cause of this error is attempting to pass a lambda into a delegate.

这是C#Code

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;

namespace UserProperties;

public class GraphHandler
{
    public GraphServiceClient GraphClient { get; set; }

    public GraphHandler(string tenantId, string clientId, string clientSecret)
    {
        GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
    }
    public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
    {
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud            
        };

        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var scopes = new[] { "https://graph.microsoft.com/.default" };

        return new GraphServiceClient(clientSecretCredential, scopes);
    }

    public async Task<User?> GetUser(string userPrincipalName)
    {
        return await GraphClient.Users[userPrincipalName].GetAsync();
    }

    public void userDetail()
    {
        var user =  GraphClient.Me.GetAsync();
        Console.WriteLine(user);
    }
}

我怎么能摆脱这个,有人建议我.

我想从azure目录中获取用户详细信息.

谢谢你

推荐答案

错误102通常发生在使用100并调用101端点.

  • 100是非交互流,101端点仅与用户交互流一起工作.
  • 因此,要么切换到用户交互流,要么使用100并呼叫101端点.

授予应用程序API权限以使用100:

enter image description here

然后通过修改100来修改代码,如下所示:

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using System;
using System.Threading.Tasks;

namespace UserProperties
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var tenantId = "TenantID";
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
        }

        public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
        {
            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            return new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task userDetail()
        {
            try
            {
                // Example usage to get user details directly
                var userId = "UserID"; // Replace with the desired user's ID
                var user = await GraphClient.Users[userId].GetAsync();

                // Print user ID and DisplayName
                Console.WriteLine($"User ID: {user.Id}");
                Console.WriteLine($"Display Name: {user.DisplayName}");
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting user details: {ex.Message}");
            }
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            GraphHandler handler = new GraphHandler();

            // Example usage to get my details
            await handler.userDetail();
        }
    }
}

The user details displayed successfully like below:

![enter image description here](https://i.imgur.com/loOGkB7.png)

如果您想调用101端点,则授予User.Read委托API权限,并参考MsDoc (except Client credentials provider choose any of the flow)并 Select 交互流进行认证.

100

To get the User Profile Photo, use the below code:

using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;

namespace UserProperties
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var tenantId = "TenantID";
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
        }

        public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
        {
            var options = new TokenCredentialOptions
            {
                AuthorityHost = Azure.Identity.AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new Azure.Identity.ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            return new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task<User> GetUser(string userId)
        {
            try
            {
                var user = await GraphClient.Users[userId].GetAsync();
                return user;
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting user details: {ex.Message}");
                return null;
            }
        }

        public async Task PrintProfilePicture(string userId)
        {
            var user = await GetUser(userId);
            if (user != null)
            {
                try
                {
                    using (var photoStream = await GraphClient.Users[userId].Photo.Content.GetAsync())
                    {
                        var fileName = $"{userId}_profile_pic.jpg";
                        using (var fileStream = File.Create(fileName))
                        {
                            await photoStream.CopyToAsync(fileStream);
                            Console.WriteLine($"Profile picture saved as: {fileName}");
                        }
                    }
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine($"Error downloading profile picture: {ex.Message}");
                }
            }
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var handler = new GraphHandler();
            var userId = "UserID"; // Replace with the desired user's ID
            await handler.PrintProfilePicture(userId);
        }
    }
}

enter image description here

enter image description here

Reference:

Get a user - Microsoft Graph v1.0 | Microsoft

Csharp相关问答推荐

总是丢弃返回的任务和使方法puc无效之间有区别吗?

EF Core判断是否应用了AsSplitQuery()

为什么这个Reflection. Emit代码会导致一个DDL ViolationException?

如何在Reflection. Emit中使用具有运行时定义的类型参数的泛型类型

为什么我的ASP.NET核心MVC应用程序要为HTML元素添加一些标识符?

在C#WinUI中,一个关于System的崩溃."由于未知原因导致执行不例外"

如何在C#中从正则表达式中匹配一些数字但排除一些常量(也是数字)

如何使用NumberFormatInfo

CS1660无法将lambda表达式转换为类型INavigationBase,因为它不是委托类型

当前代码Cosmos DB 3.37.1:PartitionKey key key mismatch exception

.NET并发词典交换值

Lambda表达式如何与隐式强制转换一起工作?

RX操作员使用先前值进行扫描,信号来自值本身

源代码生成器:CS8795分部方法';Class1.GetS2(字符串)';必须有实现部分,因为它有可访问性修饰符?

为什么我的伺服电机不动,下面的代码?

为什么我不能从我的异步任务方法中返回异步任务方法?

流畅的验证--如何为属性重用规则?

映射器-如何映射到多个实体

.NET文档对继承的困惑

如何在C#中抽象Vector256;T<;的逻辑以支持不同的硬件配置?