跳至页脚内容
.NET 帮助

MS Graph .NET(开发人员如何使用)

MS Graph .NET 是一个用于与 Microsoft Graph API 交互的数据访问工具,是 Azure Active Directory (Azure AD) 生态系统的核心组件。 Microsoft Graph 是 Microsoft 365 中数据和智能的门户。它允许开发人员访问、管理和分析跨各种 Microsoft 服务的数据。 Microsoft Graph 客户端库通过提供一组方法来轻松地与 API 互动,从而简化了这个过程。

IronPDF 是一个用于在 .NET 应用程序中生成 PDF 文档的库。 它将 HTML 转换为 PDF,使其在自动生成报告、发票和文档时非常有用。 IronPDF 非常适合 .NET 应用程序,为 PDF 生成提供了一种简单的方法。

将MS Graph .NET和IronPDF结合使用,开发人员可以创建能够操作Microsoft 365数据并生成PDF文档的应用程序。 这种组合对于需要从 Microsoft 服务中获取数据并需要以标准化文档格式显示该数据的业务应用程序开发非常强大。

开始使用 MS Graph .NET

在 .NET 项目中设置 MS Graph .NET

要有效使用 MS Graph .NET,特别是在使用 .NET Core 项目中的用户 ID时,设置您的 .NET 项目是第一步。以下是步骤:

  1. 打开 NuGet 包管理器。
  2. 搜索 Microsoft.Graph
  3. 安装 Microsoft.Graph 包。

MS Graph .NET(开发人员如何使用它):图1

此过程将 MS Graph .NET 添加到您的项目中。 现在,您已准备好开始使用它进行编码了。

基本代码示例

假设您想检索当前用户的个人资料信息。 这是一个简单的代码示例:

// Required namespaces
using Azure.Identity;
using Microsoft.Graph;

// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };

// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// Fetching current user's profile information
var user = await graphClient.Me
    .Request()
    .GetAsync();

// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");
// Required namespaces
using Azure.Identity;
using Microsoft.Graph;

// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };

// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// Fetching current user's profile information
var user = await graphClient.Me
    .Request()
    .GetAsync();

// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");
' Required namespaces
Imports Azure.Identity
Imports Microsoft.Graph

' Defining necessary credentials and scope
Private clientId = "Your_Application_Id"
Private tenantId = "Your_Tenant_Id"
Private clientSecret = "Your_Client_Secret"
Private scopes = { "User.Read" }

' Configuring TokenCredentialOptions for Azure Public Cloud
Private options = New TokenCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}

' Authenticating using client credentials
Private clientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)

' Creating a new instance of GraphServiceClient
Private graphClient = New GraphServiceClient(clientSecretCredential, scopes)

' Fetching current user's profile information
Private user = await graphClient.Me.Request().GetAsync()

' Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!")
$vbLabelText   $csharpLabel

此代码片段演示了如何创建一个新的 GraphServiceClient 实例,利用 Azure AD 身份验证的客户端密钥。 它使用客户端凭据进行身份验证。 然后,它检索当前用户的显示名称。 完成此步骤后,确保 MS Graph .NET 以及您的身份验证提供程序配置已添加到您的项目中。

MS Graph .NET 的功能

检索用户电子邮件

要从用户的 Microsoft 账户邮箱中检索电子邮件,请使用 Mail.Read 权限。 以下是如何列出最近的电子邮件的方法:

// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10)
    .GetAsync();

// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10)
    .GetAsync();

// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
' Retrieving the top 10 messages from the user's mailbox
Dim messages = Await graphClient.Me.Messages.Request().Top(10).GetAsync()

' Iterating through the messages and printing their subjects
For Each message In messages
	Console.WriteLine($"Subject: {message.Subject}")
Next message
$vbLabelText   $csharpLabel

此代码列出了用户收件箱中前 10 封电子邮件的主题。

发送电子邮件

发送电子邮件涉及创建一个Message对象并发送它:

// Creating a message to be sent
var message = new Message
{
    Subject = "Hello from MS Graph .NET",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "Hello, this is a test email."
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "recipient@example.com"
            }
        }
    }
};

// Sending the email
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
// Creating a message to be sent
var message = new Message
{
    Subject = "Hello from MS Graph .NET",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "Hello, this is a test email."
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "recipient@example.com"
            }
        }
    }
};

// Sending the email
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
' Creating a message to be sent
Dim message As New Message With {
	.Subject = "Hello from MS Graph .NET",
	.Body = New ItemBody With {
		.ContentType = BodyType.Text,
		.Content = "Hello, this is a test email."
	},
	.ToRecipients = New List(Of Recipient)() From {
		New Recipient With {
			.EmailAddress = New EmailAddress With {.Address = "recipient@example.com"}
		}
	}
}

' Sending the email
Await graphClient.Me.SendMail(message, Nothing).Request().PostAsync()
$vbLabelText   $csharpLabel

这会发送一封带有简单文本正文的电子邮件。

管理日历事件

要向用户的日历添加事件:

// Creating a calendar event
var @event = new Event
{
    Subject = "Team Meeting",
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = "Discuss project updates."
    },
    Start = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T12:00:00",
        TimeZone = "Pacific Standard Time"
    },
    End = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T14:00:00",
        TimeZone = "Pacific Standard Time"
    },
    Location = new Location
    {
        DisplayName = "Conference Room 1"
    }
};

// Adding the event to the user's calendar
await graphClient.Me.Events
    .Request()
    .AddAsync(@event);
// Creating a calendar event
var @event = new Event
{
    Subject = "Team Meeting",
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = "Discuss project updates."
    },
    Start = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T12:00:00",
        TimeZone = "Pacific Standard Time"
    },
    End = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T14:00:00",
        TimeZone = "Pacific Standard Time"
    },
    Location = new Location
    {
        DisplayName = "Conference Room 1"
    }
};

// Adding the event to the user's calendar
await graphClient.Me.Events
    .Request()
    .AddAsync(@event);
' Creating a calendar event
Dim [event] As [Event] = New [Event] With {
	.Subject = "Team Meeting",
	.Body = New ItemBody With {
		.ContentType = BodyType.Html,
		.Content = "Discuss project updates."
	},
	.Start = New DateTimeTimeZone With {
		.DateTime = "2024-04-15T12:00:00",
		.TimeZone = "Pacific Standard Time"
	},
	.End = New DateTimeTimeZone With {
		.DateTime = "2024-04-15T14:00:00",
		.TimeZone = "Pacific Standard Time"
	},
	.Location = New Location With {.DisplayName = "Conference Room 1"}
}

' Adding the event to the user's calendar
Await graphClient.Me.Events.Request().AddAsync([event])
$vbLabelText   $csharpLabel

此代码在日历中安排了一个新的事件。

访问 OneDrive 文件

要列出用户 OneDrive 根目录中的文件:

// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();

// Printing each file's name
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();

// Printing each file's name
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
' Retrieving files from the root OneDrive folder
Dim files = Await graphClient.Me.Drive.Root.Children.Request().GetAsync()

' Printing each file's name
For Each file In files
	Console.WriteLine(file.Name)
Next file
$vbLabelText   $csharpLabel

此代码打印 OneDrive 根目录中文件的名称。

使用 Teams

要获取用户所属的团队列表:

// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();

// Printing each team's display name
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();

// Printing each team's display name
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
' Retrieving teams that the user is part of
Dim teams = Await graphClient.Me.JoinedTeams.Request().GetAsync()

' Printing each team's display name
For Each team In teams
	Console.WriteLine($"Team name: {team.DisplayName}")
Next team
$vbLabelText   $csharpLabel

这会列出用户所属团队的名称。

这些功能展示了 MS Graph .NET 的强大和多功能性。 它们展示了如何将 Microsoft 365 服务集成到您的应用程序中。

将 MS Graph .NET 与 IronPDF 集成

MS Graph .NET(开发人员如何使用它):图 2

如果您希望在 .NET 应用程序中处理 PDF,IronPDF Library for .NET Developers 是一个不错的选择。它是一个库,使您的应用程序能够读取、创建和操作 PDF 文件,而无需任何其他外部 PDF 工具或软件。

用例:将 IronPDF 与 MS Graph .NET 合并

假设您正在构建一个应用程序,需要从 Microsoft 365 获取文档,比如报告或发票,并将它们转换为 PDF。 MS Graph .NET 允许您与 Microsoft 365 资源交互,包括存储在 OneDrive 或 SharePoint 中的文件。 然后可以使用 IronPDF 将这些文档转换为 PDF。 这种组合在自动报告生成或以 PDF 格式存档电子邮件和附件以便轻松分发时尤其有用。

代码示例:从 MS Graph 到 PDF

让我们来走一个简单的例子。 我们将使用 MS Graph .NET 从 OneDrive 获取一个文档,然后使用 IronPDF 将该文档转换为 PDF。 我假设您已经设置好了 MSGraph 的身份验证; 如果没有,Microsoft 的网站上有大量文档可以帮助您入门。

// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Setting up the GraphServiceClient with a DelegateAuthenticationProvider
        var graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    // Insert code to acquire token
                    string accessToken = await GetAccessTokenAsync();
                    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                }));

        // Replace 'itemId' with the ID of your document in OneDrive
        var stream = await graphClient.Me.Drive.Items["itemId"].Content.Request().GetAsync();

        // IronPDF setup to convert the fetched file to PDF
        var renderer = new HtmlToPdf();
        var pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream));

        // Save the PDF to a file
        pdfDocument.SaveAs("YourDocument.pdf");
    }

    // Method to convert a Stream to a String
    static string StreamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }

    // Method to obtain the access token
    static async Task<string> GetAccessTokenAsync()
    {
        // Implement your authentication logic here to return the access token
        return "your_access_token";
    }
}
// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Setting up the GraphServiceClient with a DelegateAuthenticationProvider
        var graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    // Insert code to acquire token
                    string accessToken = await GetAccessTokenAsync();
                    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                }));

        // Replace 'itemId' with the ID of your document in OneDrive
        var stream = await graphClient.Me.Drive.Items["itemId"].Content.Request().GetAsync();

        // IronPDF setup to convert the fetched file to PDF
        var renderer = new HtmlToPdf();
        var pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream));

        // Save the PDF to a file
        pdfDocument.SaveAs("YourDocument.pdf");
    }

    // Method to convert a Stream to a String
    static string StreamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }

    // Method to obtain the access token
    static async Task<string> GetAccessTokenAsync()
    {
        // Implement your authentication logic here to return the access token
        return "your_access_token";
    }
}
' Simplified example, ensure to handle exceptions and errors appropriately.
Imports Microsoft.Graph
Imports IronPdf
Imports System.IO
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Setting up the GraphServiceClient with a DelegateAuthenticationProvider
		Dim graphClient = New GraphServiceClient(New DelegateAuthenticationProvider(Async Sub(requestMessage)
					' Insert code to acquire token
					Dim accessToken As String = Await GetAccessTokenAsync()
					requestMessage.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken)
		End Sub))

		' Replace 'itemId' with the ID of your document in OneDrive
		Dim stream = Await graphClient.Me.Drive.Items("itemId").Content.Request().GetAsync()

		' IronPDF setup to convert the fetched file to PDF
		Dim renderer = New HtmlToPdf()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream))

		' Save the PDF to a file
		pdfDocument.SaveAs("YourDocument.pdf")
	End Function

	' Method to convert a Stream to a String
	Private Shared Function StreamToString(ByVal stream As Stream) As String
		Using reader = New StreamReader(stream)
			Return reader.ReadToEnd()
		End Using
	End Function

	' Method to obtain the access token
	Private Shared Async Function GetAccessTokenAsync() As Task(Of String)
		' Implement your authentication logic here to return the access token
		Return "your_access_token"
	End Function
End Class
$vbLabelText   $csharpLabel

在此代码中的几点需要注意:

  • 我们使用 MSGraph 访问存储在 OneDrive 中的文件。您需要通过 Graph API 获得项目的ID。
  • 在此示例中,我们将文件流转换为字符串。 这对于 HTML 文档效果很好。 如果您处理的是二进制文件(如 Word 文档),则需要使用其他方法将这些文件转换为 PDF。
  • 在这里使用了 IronPDF 的 RenderHtmlAsPdf 方法从 HTML 字符串创建 PDF。 如果您的源文档不是 HTML,IronPDF 还提供工具可以处理其他格式。

请记住,这只是一个简化的例子。 在真实的应用程序中,您需要更牢固的身份验证处理、错误管理,并可能更优雅地处理不同的文件格式。 但这应该为您在 .NET 项目中集成 MSGraph 和 IronPDF 提供一个好的起点。

结论

MS Graph .NET(开发人员如何使用它):图3

对于希望将 Microsoft 365 功能集成到其 C# 应用程序中的开发人员而言,MS Graph .NET SDK 是必不可少的工具。 首先查看从 MS Graph .NET SDK 许可和定价信息开始,起价为 $799。

常见问题解答

MS Graph .NET如何帮助开发人员访问Microsoft 365数据?

MS Graph .NET作为开发人员访问和管理Microsoft 365数据的网关,使用微软Graph API,这是Azure Active Directory生态系统的一部分。它提供了简化数据交互流程的方法。

开发人员如何在.NET中使用Microsoft 365数据生成PDF文档?

开发人员可以使用IronPDF在.NET应用程序中通过将HTML和其他文档格式转换为PDF来生成PDF文档,利用通过MS Graph .NET访问的数据。

在项目中开始使用MS Graph .NET需要什么?

要开始使用MS Graph .NET,您需要通过NuGet包管理器安装Microsoft.Graph包,并设置使用客户端凭据的身份验证,以便与Microsoft 365服务交互。

开发人员如何使用MS Graph .NET发送电子邮件?

开发人员可以通过创建带有所需内容和接收者详情的`Message`对象,并利用`GraphServiceClient`的`SendMail`方法来发送电子邮件。

MS Graph .NET能否管理Microsoft 365账户中的日历事件?

是的,MS Graph .NET允许通过创建`Event`对象并使用如`Me.Events.Request().AddAsync(event)`等方法来管理日历事件,将事件添加到用户的日历中。

如何在.NET应用程序中将OneDrive文档转换为PDF?

要将OneDrive文档转换为PDF,可以使用MS Graph .NET获取文档,然后使用IronPDF将文档内容转换为PDF格式。

在将MS Graph .NET与IronPDF集成时需要考虑哪些因素?

在将MS Graph .NET与IronPDF集成时,需考虑稳健的身份验证、错误处理以及确保不同文件格式的兼容性,以确保转换和数据管理的顺利进行。

将MS Graph .NET与IronPDF结合使用有哪些实际应用?

将MS Graph .NET与IronPDF结合使用可以实现如生成PDF报告、将电子邮件存档为PDF或从Microsoft 365数据创建标准化商务文档等应用。

MS Graph .NET如何提高.NET应用的效率?

MS Graph .NET通过提供对Microsoft 365服务的精简访问来提高效率,使开发人员能够以最少的代码检索、管理和处理数据,从而增强生产力和应用能力。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。