1

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.

3
  • 1
    Are you using the Andriod Emulator ? Commented Apr 23, 2018 at 11:22
  • i have my android in dev mode Commented Apr 23, 2018 at 11:41
  • what is the exception? Commented Apr 23, 2018 at 12:41

4 Answers 4

3

If you are using the Andriod emulator

localhost (127.0.0.1) refers to the device's own loopback service, not the one on your machine as you may expect.

You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.

Additionally, if you are running this rest service from IISExpress you will have more problems again, and you will have to set up the configuration to except remote calls

Sign up to request clarification or add additional context in comments.

2 Comments

sorry forgot to mention i changed to localhost (shouldnt have) but i code it is my IP address, as i have it bridged with my VirtualBox that has client program where i got the client key for API access
Then you should probably have a look at the InnerException for more detail
1

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.

Comments

1

The problem is you're calling to localhost.

When you move it to your app localhost is your device or emulator. Supply the address of the actual server where your server application is running. This can be local or remote, as long as it can be reached over the same network.

While testing, it will probably start with 192.168.x.x or 10.x.x.x

1 Comment

sorry forgot to mention i changed to localhost (shouldnt have) but i code it is my IP address, as i have it bridged with my VirtualBox that has client program where i got the client key for API access.
0

Other answers have already addressed the localhost issue.

In addition, async void should be avoided as exceptions thrown by async void methods are unable to be caught because of their fire and forget nature. This can make your code unstable.

Reference Async/Await - Best Practices in Asynchronous Programming

The one exception to that rule is for event handlers.

Refactor GetRoles() to return async Task and add an event and handler to the page

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

    public MainPage() {
        InitializeComponent();
        DataLoading += OnRolesLoading;
        RolesLoading(this, EventArgs.Empty);
    }

    private event EventHandler RolesLoading = delegate { };

    private async void OnRolesLoading(object sender, EventArgs args) {
        //DataLoading -= OnRolesLoading; //Optional
        try {
            await GetRoles();
        } catch {
            //...handler error
        }
    }

    private async Task GetRoles() {
        var result = await _client.GetStringAsync("{endpoint here}");
        var role = JsonConvert.DeserializeObject<List<Roles>>(result);
        RoleListView.ItemsSource = role;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.