json 在C#中从REST API服务获取内容

2admgd59  于 5个月前  发布在  C#
关注(0)|答案(2)|浏览(68)

我想从REST API服务中获取内容。我有一个Uri,它会返回一个JSON内容。如下所示:

{
    "data": {
        "id": "2",
        "type": "people",
        "attributes": {
            "email": "[email protected]",
            "name": "My Name",
            "gender": "M",
            "cpf": null,
            "cnpj": null,
            "rg": null,
            "person-type": "NATURAL"
        }
    }
}

字符串
这是我的代码,但我不知道,我不能得到的内容。有人可以帮助我。我只是想得到我的代码背后的内容。

async Task InitializeUserData()
    {
        var AppToken = Application.Current.Properties["AppToken"];
        var AppUid = Application.Current.Properties["AppUid"];
        var AppClientHeader = Application.Current.Properties["AppClientHeader"];

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://api.xxx.com/v1/profile");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Access-Token", AppToken.ToString());
            client.DefaultRequestHeaders.TryAddWithoutValidation("Client", AppClientHeader.ToString());
            client.DefaultRequestHeaders.TryAddWithoutValidation("uid", AppUid.ToString());
            HttpResponseMessage response = client.GetAsync("").Result;

            if (response.IsSuccessStatusCode)
            {
                var contents = await response.Content.ReadAsStringAsync();
            }
        }
    }

2izufjch

2izufjch1#

您必须在BaseAddress URI的末尾**放置一个斜杠/,并且不能在您的相对URI的开头放置一个斜杠,如以下示例所示。

client.BaseAddress = new Uri("https://api.xxx.com/v1/profile/");
//https://api.xxx.com/v1/profile"/"

HttpResponseMessage response = client.GetAsync("").Result;
if (response.IsSuccessStatusCode)
{
    var contents = await response.Content.ReadAsStringAsync();
}

字符串
参考MS的MCalling a Web API From a .NET Client

nxowjjhe

nxowjjhe2#

我看到你的错误已经被处理了,但是我建议你看看Flurl。它会让你在写这个请求的时候更容易,并且会让你的代码比使用HttpClient更漂亮(因为它的语法流畅)。
阅读Flurl's github pageFlurl's documentation的更多信息

相关问题