SharePoint Integration in .NET Core
Step-by-Step Guide to Integrating SharePoint with .NET Core: From Basics to Advanced Scenarios with Microsoft Graph API
Integrating SharePoint with a .NET Core application involves understanding various SharePoint APIs, setting up your .NET Core project, and implementing essential features. This guide provides a comprehensive walkthrough, covering everything from initial setup to advanced scenarios using Microsoft Graph API.
Understanding SharePoint APIs
- The SharePoint REST API enables developers to interact with SharePoint data using HTTP requests. This API supports CRUD operations — Create, Read, Update, and Delete — on SharePoint lists and libraries, making it suitable for straightforward data manipulation tasks.
- The Microsoft Graph API is a unified endpoint for accessing multiple Microsoft 365 services, including SharePoint. It offers a broader set of features than the SharePoint REST API and allows for complex integrations with services like OneDrive, Outlook, and Teams.
When to use which API
- SharePoint REST API: Ideal for basic CRUD operations on SharePoint lists and libraries.
- Microsoft Graph API: Best for advanced scenarios requiring integration with multiple Microsoft 365 services or enhanced capabilities not available in the SharePoint REST API.
Setting up your .NET Core project
- Install .NET Core SDK: Ensure you have the latest version of the .NET Core SDK installed.
- Create a new project:
dotnet new console -n SharePointIntegration
cd SharePointIntegration
Adding necessary NuGet packages
Install the required NuGet packages for authentication and HTTP requests:
dotnet add package Microsoft.Identity.Client
dotnet add package System.Net.Http
Configuring authentication and permissions
Register your application in Azure AD:
- Navigate to the Azure portal.
- Go to “Azure Active Directory” -> “App registrations”
3. Register a new application and note the client ID, tenant ID, and client secret.
Configure authentication in your application:
using Microsoft.Identity.Client;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
public class SharePointService
{
private readonly string clientId;
private readonly string tenantId;
private readonly string clientSecret;
private readonly string authority;
private readonly string scope;
public SharePointService(string clientId, string tenantId, string clientSecret)
{
this.clientId = clientId;
this.tenantId = tenantId;
this.clientSecret = clientSecret;
this.authority = $"https://login.microsoftonline.com/{tenantId}";
this.scope = "https://graph.microsoft.com/.default"; // or SharePoint scope
}
public async Task<string> GetAccessTokenAsync()
{
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
var result = await app.AcquireTokenForClient(new[] { scope }).ExecuteAsync();
return result.AccessToken;
}
}
Connecting to SharePoint
Use the access token obtained from Azure AD to authenticate with SharePoint:
public async Task<string> GetSharePointSiteDataAsync(string siteUrl)
{
var accessToken = await GetAccessTokenAsync();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.GetAsync($"{siteUrl}/_api/web");
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new HttpRequestException("Failed to fetch data from SharePoint");
}
}
}
Using the REST API to interact with SharePoint
Example: Retrieving data from a SharePoint list.
public async Task<string> GetListItemsAsync(string siteUrl, string listName)
{
var accessToken = await GetAccessTokenAsync();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.GetAsync($"{siteUrl}/_api/web/lists/getbytitle('{listName}')/items");
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new HttpRequestException("Failed to fetch list items from SharePoint");
}
}
}
Implementing key features: Reading and writing data to SharePoint
· Reading Data: Use HTTP GET requests to fetch data from SharePoint lists and libraries.
· Writing Data: Use HTTP POST, PUT, or PATCH requests to create or update items in SharePoint lists.
Handling files and documents in SharePoint libraries
Example: Uploading a File to a SharePoint Document Library.
public async Task UploadFileAsync(string siteUrl, string libraryName, string filePath)
{
var accessToken = await GetAccessTokenAsync();
var fileBytes = System.IO.File.ReadAllBytes(filePath);
var fileName = System.IO.Path.GetFileName(filePath);
var uploadUrl = $"{siteUrl}/_api/web/GetFolderByServerRelativeUrl('{libraryName}')/Files/add(url='{fileName}',overwrite=true)";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = new ByteArrayContent(fileBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = await client.PostAsync(uploadUrl, content);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException("Failed to upload file to SharePoint");
}
}
}
Handling errors and debugging
Here are the common issues and how to resolve them:
· Authentication Failures: Verify Azure AD app registration details and ensure proper permissions.
· HTTP Request Errors: Check response status codes and error messages for troubleshooting.
Debugging tips and best practices
- Use Logging: Implement logging to monitor application flow and identify errors.
- Step Through Code: Use a debugger to step through the code and inspect variables.
Security considerations
Ensuring secure communication:
- Use HTTPS: Always communicate with SharePoint over HTTPS to encrypt data.
- Store Secrets Securely: Avoid hard-coding sensitive information; use secure storage methods.
Handling sensitive data and permissions:
- Minimal Permissions: Grant only the necessary permissions for the application to function.
- Regular Audits: Perform regular audits of permissions and access logs to maintain security.
Advanced topics
Using Microsoft Graph API for advanced scenarios
- Microsoft Graph API provides a unified interface to interact with a wide range of Microsoft 365 services, enabling more complex integrations and functionalities.
Integrating with other Microsoft 365 services
- OneDrive: Manage and interact with user files stored in OneDrive.
- Outlook: Access and manage user emails, calendars, and contacts.
- Teams: Integrate collaboration features using Microsoft Teams.
Conclusion
This guide covered the essentials of integrating SharePoint with a .NET Core application, including setting up your project, authenticating with SharePoint, and implementing key features like data manipulation and file handling.
Integrating SharePoint with .NET Core allows for the creation of robust business applications. Leveraging the capabilities of SharePoint and Microsoft 365 services can lead to innovative solutions that enhance productivity and collaboration.
References and further reading:
- SharePoint REST API Documentation
- Microsoft Graph API Documentation
- Azure AD App Registration
- GitHub Code Link
By following this guide and exploring the referenced materials, you will be well-equipped to integrate SharePoint into your .NET Core applications effectively.
For more updates on the latest tools and technologies, follow the Simform Engineering blog.