Implement graph API in Mvc 5
To implement a graph API to search users in an MVC 5 application, you can follow these steps:
Register your MVC 5 application in Azure AD and obtain the necessary client ID and secret for authentication.
Install the Microsoft.Graph NuGet package in your MVC 5 application.
Create a new class that will serve as a service for interacting with the Microsoft Graph API. In this class, you will need to set up an instance of the
GraphServiceClientclass from the Microsoft.Graph namespace.
csharpusing Microsoft.Graph; using Microsoft.Identity.Client; using System.Threading.Tasks;public class GraphService { private readonly GraphServiceClient _graphClient; publicGraphService() { var clientId = "YOUR_CLIENT_ID_HERE"; var clientSecret = "YOUR_CLIENT_SECRET_HERE"; var tenantId = "YOUR_TENANT_ID_HERE"; var authority = $"https://login.microsoftonline.com/{tenantId}"; var scopes = new[] { "https://graph.microsoft.com/.default" }; var confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(clientId) .WithClientSecret(clientSecret) .WithAuthority(new Uri(authority)) .Build(); var authenticationResult = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().Result; _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(requestMessage => { requestMessage.Headers.Authorization = newSystem.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); return Task.FromResult(0); })); } public asyncTask<User[]> SearchUsers(string query) { var request = _graphClient.Users.Request() .Select(u => new { u.Id, u.DisplayName, u.UserPrincipalName }) .Filter($"startswith(displayName,'{query}') or startswith(userPrincipalName,'{query}')");var response = await request.GetAsync(); return response.CurrentPage.ToArray(); } }In the GraphService class constructor, we're creating an instance of the GraphServiceClient class by providing the client ID and secret, as well as the tenant ID, which we use to obtain an access token for authentication.
The SearchUsers method takes a query string as a parameter and uses it to filter the search results. The request variable is set up with a filter that searches for users whose display name or user principal name starts with the query string. Finally, we call the GetAsync method on the request object to execute the search and return the results as an array of User objects.
- In your MVC controller, you can create an instance of the
GraphServiceclass and use it to search for users:
csharppublic class UserController : Controller { public async Task<ActionResult> Index(stringquery) { var service = new GraphService(); var users = await service.SearchUsers(query);return View(users); } }This example assumes that you have a view called "Index" that will display the search results. You can modify this code to fit your specific needs, such as adding error handling or using a different view.
That's it! With these steps, you should be able to search for users in your MVC 5 application using the Microsoft Graph API
Comments
Post a Comment