【问题标题】:C# How to put curly brackets in URLC#如何在URL中放置大括号
【发布时间】:2018-03-10 13:51:20
【问题描述】:

我一直在尝试从 Facebook 的图形 API 资源管理器中获取我需要的数据,但不幸的是,无法通过 C# 传递 URL 中所需的字段。

这是我目前尝试过的

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://graph.facebook.com");

            HttpResponseMessage response = client.GetAsync($"cocacola?fields=posts{id,created_time,permalink_url,message,link,type,full_picture}&access_token={textBox1.Text}").Result;
            response.EnsureSuccessStatusCode();

            string result = response.Content.ReadAsStringAsync().Result;

            var jsonRes = JsonConvert.DeserializeObject<dynamic>(result);

            var returned = jsonRes.ToString();

            MessageBox.Show(returned);
        }

这里需要做什么才能通过 API 获取数据? :)

【问题讨论】:

  • 你遇到了什么错误?
  • 问题是括号,它返回:名称'id'在当前上下文中不存在。它们被视为变量。
  • 在下面查看我的答案。

标签: c# .net api facebook-graph-api


【解决方案1】:

事实证明,存在一个问题,因为您正在使用字符串插值并且还需要在字符串中使用花括号。你必须通过加倍来逃脱它们。

HttpResponseMessage response = client.GetAsync($"cocacola?fields=posts{{id,created_time,permalink_url,message,link,type,full_picture}}&access_token={textBox1.Text}").Result;

【讨论】:

  • 非常感谢您的帮助,但是我得到的程序响应状态代码并不表示成功:500(内部服务器错误)你知道为什么:)
  • 您可以提出另一个描述该场景的问题,以免与此混淆,您将获得解决该问题的帮助。
【解决方案2】:

您的方法不正确,因为您尝试在 Url 中添加的那些变量实际上是在字符串上,您必须转义它们才能获得它们的值

因此改变

HttpResponseMessage response = client.GetAsync($"cocacola?fields=posts{id,created_time,permalink_url,message,link,type,full_picture}&access_token={textBox1.Text}").Result;

收件人

HttpResponseMessage response = client.GetAsync($"cocacola?fields="+posts{id,created_time,permalink_url,message,link,type,full_picture}+"&access_token="+{textBox1.Text}).Result;

但我不认为 {textBox1.Text}posts{id,created_time,permalink_url,message,link,type,full_picture} 意味着什么

【讨论】:

    猜你喜欢
    • 2010-12-12
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多