页面创建请求需要multipart,带有演示文稿部分

时间:2017-08-28 22:30:49

标签: c# azure-active-directory microsoft-graph

我正在使用Microsoft Graph API,并且我尝试以编程方式从C#创建oneNote页面。

    public async Task<string> GetHttpContentWithToken(string url, string token)
    {
        var httpClient = new System.Net.Http.HttpClient();
        System.Net.Http.HttpResponseMessage response;
        try
        {
            var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
            //Add the token in Authorization header
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            byte[] byteArray = File.ReadAllBytes("C:\\Users\\t-aaalle\\Documents\\Visual Studio 2015\\Projects\\WordAddIn4\\WordAddIn4\\GreetingFile.docx");
            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                {
                    HtmlConverterSettings settings = new HtmlConverterSettings()
                    {
                        PageTitle = "My Page Title"
                    };

                    XElement html = HtmlConverter.ConvertToHtml(doc, settings);
                    var httpContent = new StringContent(html.ToString(), Encoding.UTF8, "multipart/form-data");
                    string contentWord = httpContent.ToString();


                    httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders
                          .Accept
                          .Add(new MediaTypeWithQualityHeaderValue("text/html"));//ACCEPT header

                    request = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/me/onenote/sections/1-48839a74-fc3c-452d-a8a8-1eb7d891bc58/pages");
                    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                    request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",Encoding.UTF8,
                                                        "application/json");//CONTENT-TYPE header
                    request.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=----MyPartBoundary198374--");

                    contentWord = html.ToString();

                    var createMessage = new HttpRequestMessage(HttpMethod.Post, graphAPIEndpoint)
                    {
                        Content = new StringContent(contentWord, System.Text.Encoding.UTF8, "text/html")
                    };
                }
            }

            response = await httpClient.SendAsync(request);
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

我不明白当我运行程序时它意味着什么,它会抛出错误:

Page create requests require the content to be multipart, with a presentation part

修改

感谢Fei Xue已经解决了我的问题,现在我收到了一个新的错误,声明......

Write requests (excluding DELETE) must contain the Content-Type header declaration

更新的代码包括非常有见地的答案是......

public async Task<string> GetHttpContentWithToken(string url, string token)
{
    var httpClient = new System.Net.Http.HttpClient();
    System.Net.Http.HttpResponseMessage response;
    try
    {
        var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
        //Add the token in Authorization header
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        byte[] byteArray = File.ReadAllBytes("C:\\Users\\t-aaalle\\Documents\\Visual Studio 2015\\Projects\\WordAddIn4\\WordAddIn4\\GreetingFile.docx");
        using (MemoryStream memoryStream = new MemoryStream())
        {
            memoryStream.Write(byteArray, 0, byteArray.Length);
            using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
            {
                HtmlConverterSettings settings = new HtmlConverterSettings()
                {
                    PageTitle = "My Page Title"
                };

                XElement html = HtmlConverter.ConvertToHtml(doc, settings);
                var httpContent = new StringContent(html.ToString(), Encoding.UTF8, "text/html");
                string contentWord = httpContent.ToString();

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                    using (var content2 = new MultipartFormDataContent("MyPartBoundary198374"))
                    {
                        var stringContent = new StringContent("<h1>Hello</h1>", Encoding.UTF8, "text/html");
                        content2.Add(stringContent, "Presentation");


                        using (
                            var message = await client.PostAsync("https://graph.microsoft.com/v1.0/me/onenote/sections/1-48839a74-fc3c-452d-a8a8-1eb7d891bc58/pages", content2))
                        {
                            Console.WriteLine(message.StatusCode);
                        }
                    }
                }

                contentWord = html.ToString();
            }
        }

        response = await httpClient.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

要创建OneNote页面,我们需要在内容正文中指定演示部分,其中包含名称属性。这是一个使用Fiddler作为参考的例子:

POST: https://graph.microsoft.com/v1.0/me/onenote/sections/{id}/pages

authorization: bearer {token}
Content-type: multipart/form-data; boundary=MyPartBoundary198374

--MyPartBoundary198374
Content-Disposition:form-data; name="Presentation"
Content-Type:text/html

<!DOCTYPE html>
<html>
  <head>
    <title>A page with <i>rendered</i> images and an <b>attached</b> file</title>
    <meta name="created" content="2015-07-22T09:00:00-08:00" />
  </head>
  <body>
    <p>Here's an image uploaded as binary data:</p>
     <img src="name:imageBlock1" alt="an image on the page" width="300" />
  </body>
</html>
--MyPartBoundary198374
Content-Disposition: form-data; name="imageBlock1"
Content-Type: image/jpeg

<@INCLUDE *C:\me.jpg*@>
--MyPartBoundary198374--

有关此请求的更多详细信息,请参阅this link

以下是通过C#创建包含HTML的页面的代码示例:

string token = "";
using (var client = new HttpClient())
{

    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    using (var content = new MultipartFormDataContent("MyPartBoundary198374"))
    {
        var stringContent = new StringContent("<h1>Hello</h1>",Encoding.UTF8, "text/html");
        content.Add(stringContent, "Presentation");

        using (
           var message =
               await client.PostAsync("https://graph.microsoft.com/v1.0/me/onenote/sections/{id}/pages", content))
        {
            Console.WriteLine(message.StatusCode);
        }
    }
}