如何将以下 JSON 传递给带有或不带有 Javascript 序列化程序的 C# 补丁方法 [英] how to pass the following JSON to a C# patch method w or w/o Javascript serializer

查看:16
本文介绍了如何将以下 JSON 传递给带有或不带有 Javascript 序列化程序的 C# 补丁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序来访问 Visual Studio Team Services 的 REST API(以前是 Visual Studio Online).我正在关注 https://www.visualstudio.com/integrate/api/wit/工作项

我能够通过使用以下代码片段传递正确的 ID 来查询工作项:

 var uri = new Uri("https://{instance}.visualstudio.com/DefaultCollection/_apis/wit/workitems/7?api-version=1.0");GetWorkItem(uri);公共静态异步无效 GetWorkItem(Uri uri){尝试{var username = "我的用户名";var password = "我的密码";使用 (HttpClient 客户端 = 新 HttpClient()){client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", 用户名, 密码))));使用 (HttpResponseMessage response = client.GetAsync(uri).结果){response.EnsureSuccessStatusCode();string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine(responseBody);}Console.Read();}}捕获(异常前){Console.WriteLine(ex.ToString());Console.Read();}}

它正确返回此处指定的 JSON https://www.visualstudio.com/integrate/api/wit/work-items#GetalistofworkitemsByIDs

现在我正在尝试通过修改其标题来更新工作项.

https://www.visualstudio.com/integrate/api/机智/工作项#UpdateworkitemsUpdateafield

为此我写了一个方法:

 public static async void UpdateWorkItemStatus(Uri requestUri, HttpContent iContent){{var method = new HttpMethod("PATCH");var request = new HttpRequestMessage(method, requestUri){内容 = iContent};HttpResponseMessage 响应;尝试{使用 (HttpClient 客户端 = 新 HttpClient()){var username = "我的用户名";var password = "我的密码";client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", 用户名, 密码))));响应 = 等待 client.SendAsync(request);response.EnsureSuccessStatusCode();Console.WriteLine(响应);Console.Read();}}catch (TaskCanceledException e){Console.WriteLine("错误:" + e.ToString());Console.Read();}}}

我通过传递我的 json 来调用这个方法:

 var uri = new Uri("https://{instance}.visualstudio.com/DefaultCollection/_apis/wit/workitems/7?api-version=1.0");string json = new JavaScriptSerializer().Serialize(new{操作=替换",路径=字段/System.Title",value="123 新标题"});HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json-patch+json");UpdateWorkItemStatus(uri, httpContent);

这是根据https://www.visualstudio.com/integrate/api/wit/work-items#Updateworkitems

他们没有任何代码示例,所以我使用了 JavascriptSerializer但这没有任何作用.代码运行但没有输出,我的工作项目也没有被编辑.由于使用了 JavascriptSerializer,我不确定它的格式是否不正确,但我之前使用过这个类并且它运行良好.

基本上我需要传递这个 JSON :

<预><代码>[{"op": "替换","path": "fields/System.Title","value":"新标题"}]

即使不使用 JS Serializer 类,任何有关如何运行它并以正确格式传递 JSON 的帮助也将不胜感激.

最终的想法是将其转换为可以在 Unix 上运行的解释性脚本,如 curl、Python 或 Perl.对此的任何指示或建议也将不胜感激.

解决方案

我通常直接传递内容字符串,它的工作原理:

string json = "[{"op":"replace","path":"/fields/System.Title","value":"Title"}]";

您通过 JavaScriptSerializer 生成的字符串 json 缺少["和]".

顺便说一下,使用您提供的代码,如果您在 UpdateWorkItemStatus(uri, httpContent) 之前运行 GetWorkItem(uri),UpdateWorkItemStatus() 将不会运行,因为应用程序在 GetWorkItem() 之后退出.

I am working on a program to access the REST API for Visual Studio Team Services (was Visual Studio Online). I am following https://www.visualstudio.com/integrate/api/wit/work-items

I was able to query the work item by passing the correct Id using this code snippet:

 var uri = new Uri("https://{instance}.visualstudio.com/DefaultCollection/_apis/wit/workitems/7?api-version=1.0");
 GetWorkItem(uri);

 public static async void GetWorkItem(Uri uri)
    {
        try
        {
            var username = "my username";
            var password = " my pass word";

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(
                        ASCIIEncoding.ASCII.GetBytes(
                            string.Format("{0}:{1}", username, password))));

                using (HttpResponseMessage response = client.GetAsync(uri)

                    .Result)
                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    Console.WriteLine(responseBody);
                }
                Console.Read();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Console.Read();
        }
    }

It correctly returns a JSON as specified here https://www.visualstudio.com/integrate/api/wit/work-items#GetalistofworkitemsByIDs

Now I am trying to update the work item by modifying its title .

https://www.visualstudio.com/integrate/api/wit/work-items#UpdateworkitemsUpdateafield

For this I wrote a method :

 public static async void UpdateWorkItemStatus(Uri requestUri, HttpContent iContent)
        {
        {
            var method = new HttpMethod("PATCH");

            var request = new HttpRequestMessage(method, requestUri)
            {
                Content = iContent
            };

            HttpResponseMessage response;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    var username = "my username";
                    var password = "my password";

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                        Convert.ToBase64String(
                            ASCIIEncoding.ASCII.GetBytes(
                                string.Format("{0}:{1}", username, password))));

                    response = await client.SendAsync(request);
                    response.EnsureSuccessStatusCode();
                    Console.WriteLine(response);

                    Console.Read();
                }
            }
            catch (TaskCanceledException e)
            {
                Console.WriteLine("ERROR: " + e.ToString());
                Console.Read();
            }

        }
    }

I am calling this method by passing my json :

 var uri = new Uri("https://{instance}.visualstudio.com/DefaultCollection/_apis/wit/workitems/7?api-version=1.0");
         string json = new JavaScriptSerializer().Serialize(new
            {
               op="replace",
               path="fields/System.Title",
               value=" 123 New Title"

            });

        HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json-patch+json");

        UpdateWorkItemStatus(uri, httpContent);

This is in accordance with the information in https://www.visualstudio.com/integrate/api/wit/work-items#Updateworkitems

They don't have any code samples so I used JavascriptSerializer But this doesn't do anything . The code runs but gives no output and my work item is also not edited. I am not sure if it is incorrect in format due to using JavascriptSerializer but I have used this class before and it has worked well.

Basically I need to pass this JSON :

[
  {
    "op": "replace",
    "path": "fields/System.Title",
    "value":"New Title"
  }
]

Any help on how to get this running and pass the JSON in a right format would be appreciated even if without using the JS Serializer class.

Eventually the idea is to convert this to an interpreted script that can run on Unix, like curl, Python or Perl. Any pointers or recommendations on that would also be appreciated.

解决方案

I usually pass the content strings directly and it works:

string json = "[{"op":"replace","path":"/fields/System.Title","value":"Title"}]";

The string json you generated by JavaScriptSerializer is missing "[" and "]".

By the way, with the code you provided, if you run GetWorkItem(uri) before UpdateWorkItemStatus(uri, httpContent), UpdateWorkItemStatus() won't run since the app exit after GetWorkItem().

这篇关于如何将以下 JSON 传递给带有或不带有 Javascript 序列化程序的 C# 补丁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆