获得在C#从REST API服务内容

问题描述:

我想要一份获得来自REST API的服务内容。我有一个Uri,它返回了我的json内容。就像下面这个例子:获得在C#从REST API服务内容

{ 
    "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(); 
      } 
     } 
    } 
+0

什么是错误阅读? – Kzrystof

+0

您的JSON是无效的。 – Valkyrie

+0

基址应为'https://api.xxx.com/v1'然后调用*变种响应=等待client.GetAsync(“个人资料/ 2”); * –

必须发生在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的Docs Calling a Web API From a .NET Client

我看到你的错误已得到照顾,但我建议你看一看Flurl。这将使在写这个请求您的生活更轻松,并使用HttpClient的(因为它的流畅的语法)将会使你的代码的方式比 更美丽。

更在 Flurl's github pageFlurl's documentation