Graph API does not work in console app but works in UI app.

Chris Zohno 0 Reputation points
2024-11-09T02:18:35.38+00:00

Hi,

I am created an app using Graph API. I need to run the app as a Windows Form UI app and as a console app. I am using client credential flow. After setting up all required app permissions, my Windows Form UI app works fine. I can retrieve various data from Azure AD. But if I run the same code as a console app, it does not work. It stuck in the await GetAsync() statement. My code is like this:

     try {

           GraphServiceClient graphServiceClient = getGraphServiceClient();   

           var exuser = await graphServiceClient.Users[upn].GetAsync();

     }

      catch (Exception ex)

        {

            //exception handling here

            return false;

        }

This code is to check if a user has been synched from AD to Azure. If not, this code should throw "not found" exception. In UI mode, I do see exceptions caught. But in console mode, exceptions are not caught. Maybe exceptions are handled differently in UI mode and console mode?

Anyone can point me to where I should look into?

Microsoft Security Microsoft Graph
{count} votes

1 answer

Sort by: Most helpful
  1. CarlZhao-MSFT 46,366 Reputation points
    2024-11-11T08:10:09.7666667+00:00

    Hi @Chris Zohno

    In SDK 5.0 and above, I recommend that you use OdataError instances to catch exceptions.

    try
    {
        var exuser = await graphClient.Users["******@xxxxxx.onmicrosoft.com"].GetAsync();
    }
    catch (ODataError odataError)
    {
        Console.WriteLine(odataError.Error.Code);
        Console.WriteLine(odataError.Error.Message);
    }
    

    User's image

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.