使用REST和HTTPClient在SP2013中创建文件夹

知道不多

我正在尝试使用HTTPClient和REST在SP2013中创建一个文件夹。

以下是对应用程序的要求和约束

  1. 我需要使用REST在2013文档库中创建一个文件夹。不允许CSOM。

  2. 该程序必须是C#控制台应用程序。

  3. 我必须仅使用HTTPClient进行对Web服务的所有调用。不应使用其他任何旧类或库。

  4. 集成身份验证是必须的。您不得在此处在代码中输入您的用户名和密码。它必须使用进程的标识。

基于这些约束,我编写了这段代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RESTCreateFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            int retVal = p.Process().Result;            
        }

        private async Task<int> Process()
        {
            string url = "http://bi.abhi.com/testweb/";
            using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
            {
                client.BaseAddress = new System.Uri(url);
                client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
                string digest = await GetDigest(client);
                Console.WriteLine("Digest " + digest);
                try
                {
                    await CreateFolder(client, digest);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }
            return 0;
        }

        private object CreateRequest(string folderPath)
        {
            var type = new { type = "SP.Folder" };
            var request = new { __metadata = type, ServerRelativeUrl = folderPath };
            return request;
        }

        private async Task CreateFolder(HttpClient client, string digest)
        {
            client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
            var request = CreateRequest("/test/foo");
            string json = JsonConvert.SerializeObject(request);
            StringContent strContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
            strContent.Headers.ContentLength = json.Length;
            HttpResponseMessage response = await client.PostAsync("_api/web/folders", strContent);
            //response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
            else
            {
                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.ReasonPhrase);
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
        }

        public async Task<string> GetDigest(HttpClient client)
        {
            string retVal = null;
            string cmd = "_api/contextinfo";                       
            HttpResponseMessage response = await client.PostAsJsonAsync(cmd, "");
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                JToken t = JToken.Parse(content);
                retVal = t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
            }
            return retVal;
        }
    }
}

但是,此代码始终会因BAD REQUEST而失败。

您能否使“此”代码正常工作,并让我知道您如何解决它。我在MSDN上找到了很多文章,但是它们都使用了我无法使用的WebRequest的旧方法。我必须使用HttpClient。

编辑::

这是从提琴手那里捕获的原始请求

POST http://bi.abhi.com/testweb/_api/web/folders HTTP/1.1
Accept: application/json; odata=verbose
X-RequestDigest: 0x8B2A0904D5056E49DB886A72D59A86264A000F9AB14CE728407ECCD6F4369A7AD2585967BE9A57085344A5ACC99A4DA61D59E5EFA9A54B9B83564B2EA736F7F4,21 Aug 2014 20:24:15 -0000
Content-Type: application/json; charset=utf-8
Host: bi.abhi.com
Content-Length: 67
Expect: 100-continue

{"__metadata":{"type":"SP.Folder"},"ServerRelativeUrl":"/test/foo"}

这是提琴手的原始回应

HTTP/1.1 400 Bad Request
Cache-Control: private, max-age=0
Transfer-Encoding: chunked
Content-Type: application/json;odata=verbose;charset=utf-8
Expires: Wed, 06 Aug 2014 20:24:15 GMT
Last-Modified: Thu, 21 Aug 2014 20:24:15 GMT
Server: Microsoft-IIS/8.0
X-SharePointHealthScore: 0
SPClientServiceRequestDuration: 4
X-AspNet-Version: 4.0.30319
SPRequestGuid: a9c6b09c-9340-10e2-0000-093d0491623a
request-id: a9c6b09c-9340-10e2-0000-093d0491623a
X-RequestDigest: 0x8B2A0904D5056E49DB886A72D59A86264A000F9AB14CE728407ECCD6F4369A7AD2585967BE9A57085344A5ACC99A4DA61D59E5EFA9A54B9B83564B2EA736F7F4,21 Aug 2014 20:24:15 -0000
X-FRAME-OPTIONS: SAMEORIGIN
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 15.0.0.4569
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
Date: Thu, 21 Aug 2014 20:24:14 GMT

e6
{"error":{"code":"-1, System.InvalidOperationException","message":{"lang":"en-US","value":"The required version of WcfDataServices is missing. Please refer to http://go.microsoft.com/fwlink/?LinkId=321931 for more information."}}}
0

我已经完全修补了服务器环境,并且没有新的更新要应用。所以我不知道为什么它说缺少必需的wcfdata服务。

知道不多

我解决了这个问题。使用了提供的答案

http://social.msdn.microsoft.com/Forums/zh-CN/a58a4bec-e936-48f9-b881-bc0a7ebb7f8a/create-a-folder-in-sp2013-document-library-using-rest-using-http-客户?论坛= appsforsharepoint

显然,在使用StringContent时,必须将其设置为“ application / json; odata = verbose”,否则会收到400错误的请求。StringContent设置Content-Type标头。

StringContent strContent = new StringContent(json);
strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");

我的完整代码现在看起来像

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        int retVal = p.Process().Result;            
    }

    private async Task<int> Process()
    {
        string url = "http://bi.abhi.com/testweb/";
        using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
        {
            client.BaseAddress = new System.Uri(url);
            client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
            string digest = await GetDigest(client);
            Console.WriteLine("Digest " + digest);
            try
            {
                await CreateFolder(client, digest);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
        return 0;
    }

    private object CreateRequest(string folderPath)
    {
        var type = new { type = "SP.Folder" };
        var request = new { __metadata = type, ServerRelativeUrl = folderPath };
        return request;
    }

    private async Task CreateFolder(HttpClient client, string digest)
    {
        client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
        var request = CreateRequest("foo");
        string json = JsonConvert.SerializeObject(request);
        StringContent strContent = new StringContent(json);
        strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
        HttpResponseMessage response = await client.PostAsync("_api/web/getfolderbyserverrelativeurl('test/test123/')/folders", strContent);
        //response.EnsureSuccessStatusCode();
        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.ReasonPhrase);
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }

    public async Task<string> GetDigest(HttpClient client)
    {
        string retVal = null;
        string cmd = "_api/contextinfo";                       
        HttpResponseMessage response = await client.PostAsJsonAsync(cmd, "");
        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();
            JToken t = JToken.Parse(content);
            retVal = t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }
        return retVal;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用REST和HTTPClient在SP2013中创建文件夹

来自分类Dev

在SharePoint 2013中以编程方式创建文件夹

来自分类Dev

如何使用powershell在azure web app中创建文件夹和添加文件

来自分类Dev

使用Terraform在s3存储桶中创建文件夹和子文件夹

来自分类Dev

在文件夹中创建文件

来自分类Dev

使用.txt输入文件创建文件夹和子文件夹

来自分类Dev

使用python在Outlook 2010中创建文件夹

来自分类Dev

使用javascript在android中创建文件夹

来自分类Dev

使用 CSV 中的 powershell 创建文件夹

来自分类Dev

使用VBS创建文件夹和子文件夹

来自分类Dev

在laravel中创建文件夹

来自分类Dev

在Swift中创建文件夹

来自分类Dev

在Kotlin中创建文件夹

来自分类Dev

使用WshUserEnv创建文件夹

来自分类Dev

使用Swift创建文件夹

来自分类Dev

使用OS X Automator在所选文件夹中创建文件夹

来自分类Dev

使用C#在虚拟文件夹中创建文件夹

来自分类Dev

Azure DevOps:如何使用REST API存储库在GIT存储库中创建文件夹

来自分类Dev

Azure DevOps:如何使用REST API存储库在GIT存储库中创建文件夹

来自分类Dev

从目录中随机读取文件后如何创建文件和相应的文件夹

来自分类Dev

使用javascript和Google api v3在另一个文件夹中创建文件夹快捷方式

来自分类Dev

在C ++编程中的文件夹中创建文件

来自分类Dev

如何使用客户端对象模型创建文件夹和子文件夹-Javascript

来自分类Dev

使用Java在Zip文件中重新创建文件夹结构-空文件夹

来自分类Dev

使用python创建用于创建文件夹的循环

来自分类Dev

在Powershell中创建文件夹和文件

来自分类Dev

在特定文件夹中创建文件

来自分类Dev

在Powershell中创建文件夹和文件

来自分类Dev

在文件夹中创建文件:权限被拒绝

Related 相关文章

  1. 1

    使用REST和HTTPClient在SP2013中创建文件夹

  2. 2

    在SharePoint 2013中以编程方式创建文件夹

  3. 3

    如何使用powershell在azure web app中创建文件夹和添加文件

  4. 4

    使用Terraform在s3存储桶中创建文件夹和子文件夹

  5. 5

    在文件夹中创建文件

  6. 6

    使用.txt输入文件创建文件夹和子文件夹

  7. 7

    使用python在Outlook 2010中创建文件夹

  8. 8

    使用javascript在android中创建文件夹

  9. 9

    使用 CSV 中的 powershell 创建文件夹

  10. 10

    使用VBS创建文件夹和子文件夹

  11. 11

    在laravel中创建文件夹

  12. 12

    在Swift中创建文件夹

  13. 13

    在Kotlin中创建文件夹

  14. 14

    使用WshUserEnv创建文件夹

  15. 15

    使用Swift创建文件夹

  16. 16

    使用OS X Automator在所选文件夹中创建文件夹

  17. 17

    使用C#在虚拟文件夹中创建文件夹

  18. 18

    Azure DevOps:如何使用REST API存储库在GIT存储库中创建文件夹

  19. 19

    Azure DevOps:如何使用REST API存储库在GIT存储库中创建文件夹

  20. 20

    从目录中随机读取文件后如何创建文件和相应的文件夹

  21. 21

    使用javascript和Google api v3在另一个文件夹中创建文件夹快捷方式

  22. 22

    在C ++编程中的文件夹中创建文件

  23. 23

    如何使用客户端对象模型创建文件夹和子文件夹-Javascript

  24. 24

    使用Java在Zip文件中重新创建文件夹结构-空文件夹

  25. 25

    使用python创建用于创建文件夹的循环

  26. 26

    在Powershell中创建文件夹和文件

  27. 27

    在特定文件夹中创建文件

  28. 28

    在Powershell中创建文件夹和文件

  29. 29

    在文件夹中创建文件:权限被拒绝

热门标签

归档