我想创建一个使用 PnP 核心 SDK 连接到 SharePoint 在线租户的 .net 8.0 控制台应用程序。现在我没有找到任何示例代码,所以我开发了这个控制台应用程序:-
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PnP.Core.Auth;
using PnP.Core.Model.SharePoint;
using PnP.Core.Services;
using PnP.Core.Services.Builder.Configuration;
using System;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp4
{
internal class Program
{
static async Task Main(string[] args)
{
var tenantId = "**c";
var clientId = "7***9";
var certificatePath = @"c:\CERT\SPDashBoard.pfx";
var certificatePassword = "******";
// Initialize a new service collection
var serviceCollection = new ServiceCollection();
// Load the certificate
var certificate = new X509Certificate2(certificatePath, certificatePassword, X509KeyStorageFlags.Exportable);
// Configure logging
//serviceCollection.AddLogging(builder =>
//{
// builder.AddConsole();
//});
// Add and configure PnP Core SDK
serviceCollection.AddPnPCore(options =>
{
options.PnPContext.GraphFirst = false; // Set true if you prefer to use Graph over CSOM when possible
// options.HttpRequests.UserAgent = "ISV|Contoso|ProductX";
options.Sites.Add("SiteToWorkWith", new PnPCoreSiteOptions
{
SiteUrl = "https://seagullssms.sharepoint.com/sites/Seagulls-PPM",
AuthenticationProvider = new X509CertificateAuthenticationProvider(clientId, tenantId, certificate)
});
});
// Build the service provider
var serviceProvider = serviceCollection.BuildServiceProvider();
// Use the service provider to get the IPnPContextFactory instance
var pnpContextFactory = serviceProvider.GetRequiredService<IPnPContextFactory>();
// Now you can use the IPnPContextFactory to get a PnPContext and perform operations
var context = await pnpContextFactory.CreateAsync("SiteToWorkWith");
// Example operation: Print the title of the SharePoint site
// Explicitly load the Title property of the Web
await context.Web.LoadAsync(w => w.Title);
Console.WriteLine($"Site title: {context.Web.Title}");
// Ensure to dispose the context
context.Dispose();
}
}
}
我使用自签名证书在 Active Directory 中创建了应用程序注册,并将证书安装在托管服务器内。似乎上述方法有效,我能够获得网页标题..但我不确定我的方法是否有效或可以改进?
.NET 8.0 控制台应用程序使用 PnP Core SDK 在线连接到 SharePoint,我的操作是否正确?
是的,您走在正确的道路上。您还可以向代码添加错误处理,以处理身份验证过程中或从 SharePoint 检索数据时可能发生的任何异常。
或者,您还可以使用以下示例代码,利用 Microsoft Graph API 调用在线访问 SharePoint:
创建 Azure AD 应用程序并添加所需的 API 权限:
这里我尝试列出SharePoint网站名称
using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
// Set the values for your application
string clientId = "ClientID";
string clientSecret = "ClientSecret";
string tenantId = "TenantID";
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
try
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
// Acquire an access token for the client
AuthenticationResult result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
string accessToken = result.AccessToken;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/sites?search=*");
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
// Deserialize the JSON response
JObject json = JObject.Parse(content);
// Extract the value of the "name" property for each site
foreach (var site in json["value"])
{
Console.WriteLine(site["name"]);
}
}
else
{
Console.WriteLine($"Failed to call Microsoft Graph API: {response.ReasonPhrase}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}
参考:
在 Microsoft Graph 中使用 SharePoint 网站 - Microsoft Graph v1.0 |微软