Search code examples
c#jsondotnet-httpclient

Get content from a REST API Service in C#


I`d like to get a content from an REST API service. I have an Uri that returns me a JSON content. Like this example below:

{
    "data": {
        "id": "2",
        "type": "people",
        "attributes": {
            "email": "localhost@localhost.com",
            "name": "My Name",
            "gender": "M",
            "cpf": null,
            "cnpj": null,
            "rg": null,
            "person-type": "NATURAL"
        }
    }
}

This is my code, but I don't know, I can't get the content. Someone could help me. I just like to get this content in my code behind.

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();
            }
        }
    }   

Solution

  • You must place a slash / at the end of BaseAddress URI,and must not place a slash at the begining of your relative URI , as in the following example.

    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();
    }
    

    Reference MS's Docs Calling a Web API From a .NET Client