Microsoft_Graph_REST_ASPNET_Connect.Models.GraphService.GetMyEmailAddress C# (CSharp) Method

GetMyEmailAddress() public method

public GetMyEmailAddress ( string accessToken ) : Task
accessToken string
return Task
        public async Task<string> GetMyEmailAddress(string accessToken)
        {

            // Get the current user. 
            // The app only needs the user's email address, so select the mail and userPrincipalName properties.
            // If the mail property isn't defined, userPrincipalName should map to the email for all account types. 
            string endpoint = "https://graph.microsoft.com/v1.0/me";
            string queryParameter = "?$select=mail,userPrincipalName";
            UserInfo me = new UserInfo();

            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, endpoint + queryParameter))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
                    request.Headers.Add("SampleID", "aspnet-connect-rest-sample");
                    using (HttpResponseMessage response = await client.SendAsync(request))
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            var json = JObject.Parse(await response.Content.ReadAsStringAsync());
                            me.Address = !string.IsNullOrEmpty(json.GetValue("mail").ToString()) ? json.GetValue("mail").ToString() : json.GetValue("userPrincipalName").ToString();
                        }
                        return me.Address?.Trim();
                    }
                }
            }
        }
        // Send an email message from the current user.

Usage Example

        // Test GraphService.GetMyEmailAddress method. 
        // Gets the email address of the test account.
        // Success: Retrieved email address matches test account's email address.
        public async Task GetMyEmailAddress()
        {
            // Arrange
            GraphService graphService = new GraphService();
            string emailAddress = null;

            // Act
            emailAddress = await graphService.GetMyEmailAddress(accessToken);

            // Assert
            Assert.IsTrue(emailAddress.ToLower() == userName.ToLower(), emailAddress.ToString());

        }