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

问题描述 投票:0回答:2

我想从 REST API 服务获取内容。我有一个返回 JSON 内容的 Uri。就像下面这个例子:

{
    "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();
            }
        }
    }   
c# json dotnet-httpclient
2个回答
0
投票

必须

/
URI 的末尾放置斜杠
BaseAddress
,并且不得在相对 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 的文档 从 .NET 客户端调用 Web API


0
投票

我看到你的错误已经得到解决,但我建议你看看 Flurl。它会让你在编写这个请求时变得更轻松,并且会让你的代码比 使用 HttpClient (因为其语法流畅)。

阅读更多内容 Flurl 的 github 页面Flurl 的文档

© www.soinside.com 2019 - 2024. All rights reserved.