Search code examples
c#.netrestxamarin.forms

Trying to call rest APIs, but get http request exception


I'm trying to create in Xamarin, with some restful API calls. I have already tested the API in swagger and after authorizing I get a success 200 response. However when I moved to my Xamarin project it errors out with:

http request exception

Here is my code:

public partial class MainPage : ContentPage
{
    private readonly HttpClient _client = new HttpClient();

    public MainPage()
    {
        InitializeComponent();
        GetRoles();
    }

    private async void GetRoles() 
    {
        var result = await 
     _client.GetStringAsync("http://localhost/CherwellAPI/api/V2/getroles");
        var role = JsonConvert.DeserializeObject<List<Roles>>(result);
        RoleListView.ItemsSource = role;
    }
}

}

i also have the Role Model:

 public class Roles
{
    public string RoleId { get; set; }
    public string RoleName { get; set; }
}

My xaml file is:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CherwellRolesApp"
         x:Class="CherwellRolesApp.MainPage">

<Label Text="Cherwell Roles App" TextColor="Azure" HorizontalOptions="Center" VerticalOptions="Center"></Label>

<ListView x:Name="RoleListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text="{Binding RoleName}" TextColor="Black"></Label>
                    <Label Text="{Binding RoleId}" TextColor="Black"></Label>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

</ContentPage>

If anyone has a clue to where to stair me, as it was an unhelpful exception that didn't provide anything more that the image provided. I would be grateful, as I am new to restful APIs.


Solution

  • I have had this in the past, well when just starting to learn API's etc. But Try Catching the error when no clear answer given will help (like previously mentioned!).

    It could depend on the type of API your calling; from observing the code you coud be calling an API that needs authentication/authorization aswell. This woud result in an exception, but usually you would see 401: Unauthorized etc.

    If your authenticating in the swagger tool, you will need to your IDE.