简体   繁体   中英

How to use the Microsoft graph explorer in c# console application?

I am trying to get the user group details by the JSON output. I referred some HTTP methods to get the output but I get the exception The remote server returned an error: (401) Unauthorized. instead of my expected JSON output.

My code is

public void GetJSON()
    {
        string url = string.Format("https://graph.microsoft.com/v1.0/groups");
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        webrequest.Method = "GET";
        webrequest.ContentType = "application/x-www-form-urlencoded";
        webrequest.Headers.Add("Username", "mailID@domain.com");
        webrequest.Headers.Add("Password", "mypassword");
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
        string result = string.Empty;
        result = responseStream.ReadToEnd();
        webresponse.Close();
        return result;
    }

I know there is authentication error. But I don`t know how to clear this? I can able to get the expected output in the Microsoft graph explorer but I facing this error in the console application.

Anyone know how to clear this exception? Before, my method is right or not for using Microsoft Graph API?

There are a lot of moving parts to setting up your graph client - some on the AD server and some in the client code. At a high level, these include "registering" your client app with an app key and password on the server and then configuring the client to pass these key values to the server. If you haven't already done so, take a look at the sample graph client console application available at https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console . In addition to sample source code, there are instructions on how to set up your environment and good explanation for what the code is doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM