Search code examples
c#httpdotnet-httpclient

Accessing local API with C#


I am developing an API in PHP where I return a JSON file, I perform the tests in postman and it works perfectly with the URL:

http://localhost:80/bdevApi/api/index/keyacessoUbasd42123/CategoriaExame

returning me

{
    "code": "200",
    "result": true,
    "message": "",
    "data": {
        "item": [
            {
                "id": "5",
                "descricao": "TesteDesc",
                "observacao": "TesteObs",
                "status": "1"
            },
            {
                "id": "7",
                "descricao": "TesteDesc",
                "observacao": "TesteObs",
                "status": "1"
            },
        ],
        "count": 15
    }
}

now I want to receive this information in a C # application using WPF. I've imported the client

public partial class MainWindow : Window
    {
        HttpClient client = new HttpClient();

        public MainWindow()
        {
            InitializeComponent();

            client.BaseAddress = new Uri("http://localhost:80");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            this.Loaded += MainWindow_Loaded;

            getStatusContent();
            getCategorias();
        }

        async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("/bdevApi/api/index/keyacessoUbasd42123/CategoriaExame");
                response.EnsureSuccessStatusCode(); // Lança um código de erro
                var getData = await response.Content.ReadAsAsync<IEnumerable<Categoria>>();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro : " + ex.Message);
            }
        }
}

I want to receive the information and retrieve it in my var getData, however it is loading the error

Response status code does not indicate success: 406 is not acceptable

I already tried some modified ones in the url but I did not succeed. the problem would be in the url?


Solution

  • As commented, remove the Accept header. Seems the API can't handle that correctly.

    As for your second request. You can read it as string and parse is with a library like Newtonsoft Json.NET

    var json = await content.Response.ReadAsStringAsync();
    var data = JsonConvert.DeserializeObject<IEnumerable<Categoria>>(json);