Search code examples
onenote-apimicrosoft-graph-api

Cannot POST to OneNote Client


I cannot avoid getting the following error :

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:

Here is my code:

public async Task<string> SendPostRequest(string _AccessToken)
    {
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + _AccessToken);

        string date = GetDate();
        string simpleHtml = "<html>" +
                            "<head>" +
                            "<title>A simple page created from basic HTML-formatted text</title>" +
                            "<meta name=\"created\" content=\"" + date + "\" />" +
                            "</head>" +
                            "<body>" +
                            "<p>This is a page that just contains some simple <i>formatted</i> <b>text</b></p>" +
                            "<p>Here is a <a href=\"http://www.microsoft.com\">link</a></p>" +
                            "</body>" +
                            "</html>";

        var createMessage = new HttpRequestMessage(HttpMethod.Post, _GraphAPIEndpoint)
        {
            Content = new StringContent(simpleHtml, Encoding.UTF8, "text/html")
        };

        HttpResponseMessage response = await httpClient.SendAsync(createMessage);

        return response.ToString();


    }

Here is the GraphEndpoint:

private string _GraphAPIEndpoint ="https://www.onenote.com/api/v1.0/pages";

Everything looks good with the login and authentication. I get a token etc.

Here is the code for getting my token:

 private const string _ClientID = "981c0157-69ec-4f42-8ec6-xxxxxxxxxxxxx";
       public static PublicClientApplication clientApplication = new PublicClientApplication(_ClientID);

       private AuthenticationResult authResult = null;

       authResult = await App.clientApplication.AcquireTokenAsync(_Scopes);
            if (authResult != null)
            {
               string response = await SendPostRequest(authResult.AccessToken);

            }

Solution

  • The following combination finally works:

     private string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me/onenote/pages";
    
        private string[] scopes = new string[] { "Notes.ReadWrite" };
    

    It would have been easier if some of the github OneNote Samples would have been updated.