Search code examples
c#azureazure-functionsmicrosoft-graph-api

CS:0021 Error code in Azure Function project in VS for running Microsoft Graph API with Azure Functions


I am following this tutorial on how to run Microsoft Graph API with Azure funtion:

Azure Function Tutorial

I have followed the instructions clearly and insert this code in my project:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Security.Claims;
using Azure.Identity;
using Microsoft.Graph;

namespace AZFunction1
{
    public static class Function1
    {

        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log, ClaimsPrincipal claimIdentity)
        {

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };


            var clientSecretCredential = new ClientSecretCredential(
                Constants.TenantId, Constants.AppId, Constants.ClientSecret, options);

            var graphClient = new GraphServiceClient(clientSecretCredential, Constants.scopes);
            var user = await graphClient.Users[claimIdentity.Identity.Name].GetAsync();
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(user);
            return new OkObjectResult(json);

        }
    }
}

However, I am getting this error on this code: graphClient.Users[claimIdentity.Identity.Name]

CS0021: Cannot apply indexing with [] to an expression of type 'Object'

Can someone please help me?

Any help will be much appreciated.

I tried using ChatGPT which suggest for me to use the following code but error stays the same:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Security.Claims;
using Azure.Identity;
using Microsoft.Graph;

namespace AZFunction1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log, ClaimsPrincipal claimIdentity)
        {
            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(
                Constants.TenantId, Constants.AppId, Constants.ClientSecret, options);

            var graphClient = new GraphServiceClient(clientSecretCredential, Constants.scopes);

            // Extract user ID from ClaimsPrincipal
            var userId = claimIdentity?.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            // Log the user ID
            log.LogInformation($"User ID: {userId}");

            if (string.IsNullOrEmpty(userId))
            {
                log.LogError("User identifier is null or empty.");
                return new BadRequestObjectResult("Invalid user identifier.");
            }

            try
            {
                var user = await graphClient.Users[userId].Request().GetAsync();
                var json = JsonConvert.SerializeObject(user);
                return new OkObjectResult(json);
            }
            catch (ServiceException ex)
            {
                log.LogError($"Error fetching user: {ex.Message}");
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
        }
    }
}

Solution

  • Your code is correct and it works for me without any error.

    • Make sure if your using latest stable packages.
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <RootNamespace>_78686917</RootNamespace>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Azure.Identity" Version="1.12.0" />
        <PackageReference Include="Microsoft.Graph" Version="5.56.0" />
        <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.4.0" />
      </ItemGroup>
      <ItemGroup>
        <None Update="host.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
          <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
      </ItemGroup>
    </Project>
    
    • I am using same code alike you.
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Azure.Identity;
    using Microsoft.Graph;
    using System.Security.Claims;
    using Newtonsoft.Json;
    
    namespace _78686917
    {
        public static class Function1
        {
            [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
                ILogger log, ClaimsPrincipal claimIdentity)
            {
                var options = new TokenCredentialOptions
                {
                    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
                };
    
    
                var clientSecretCredential = new ClientSecretCredential(
                    Constants.TenantId, Constants.AppId, Constants.ClientSecret, options);
    
                var graphClient = new GraphServiceClient(clientSecretCredential, Constants.scopes);
                var user = await graphClient.Users[claimIdentity.Identity.Name].GetAsync();
                var json = JsonConvert.SerializeObject(user);
                return new OkObjectResult(json);
            }
        }
    }
    
    • I have a constants class as shown below.
    
    namespace _78686917
    {
        public class Constants
        {
            public static string AppId = "52cb***818";
            public static string TenantId = "27****b0b";
            public static string ClientSecret = "oN~******Javy";
            public static string TenantName = "<tenantName>";
            public static string[] scopes = new[] { "https://graph.microsoft.com/.default" };
    
        }
    }
    
    • I have added below permissions in the registered app.

    enter image description here

    I am getting expected response both in local as well as in function app. Please ensure if you are using latest version of core tools.

    enter image description here

    enter image description here