6 Steps to Consume ASP.Net Core Web API in Xamarin | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (199)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (892)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (497)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (379)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (319)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
ASP.NET Core Web API in Xamarin

6 Steps to Consume ASP.NET Core Web API in Xamarin Applications

It is the most common requirement to access data from a web API and display it in a mobile app. To build a Xamarin application that consumes ASP.NET Core web APIs or rest services, we need HttpClient to send HTTP requests and receive HTTP responses from a web service identified by a URI. In this blog, I am going to provide a walkthrough on setting this up in 6 easy steps.

Step 1: Create an ASP.NET Core web API service or a rest service.

Use the following reference to create an ASP.NET Core web API service and host it for public access. For demo purposes, we are going to use the following hosted service.

Step 2: Create a helper class to consume the API service and return the data.

Create a helper class and name it WebAPIService with asynchronous method RefreshDataAsync and consume the API service URI.

WebAPIUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; 
//Set your REST API URL here.
var uri = new Uri(WebAPIUrl);

Step 3: Pass the service URL to process HttpClient get operation.

Use GetAsync on the base URL to retrieve the array of orders. Use the C# await option to consume the value easily.

Pass the returned object into JsonConvert.DeserializeObject to convert the JSON data into an order object and return the data to the service caller.

public async System.Threading.Tasks.Task<ObservableCollection> RefreshDataAsync()
{
    WebAPIUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Set your REST API URL here.
    var uri = new Uri(WebAPIUrl);
    try
    {
        var response = await client.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            Items = JsonConvert.DeserializeObject<ObservableCollection>(content);
            return Items;
        }
    }
    catch (Exception ex)
    {
    }
    return null;
}

Step 4: Create a model class that contains the data structure of the object received from the service call.

For example, create an Order class that contains the data structure of the object received from the demo service call.

public class Order
{
    public int OrderID { get; set; }
    public string CustomerID { get; set; }
    public int EmployeeID { get; set; }
    public double Freight { get; set; }
    public string ShipCity { get; set; }
    public bool Verified { get; set; }
    public DateTime OrderDate { get; set; }
    public string ShipName { get; set; }
    public string ShipCountry { get; set; }
    public DateTime ShippedDate { get; set; }
    public string ShipAddress { get; set; }
}

Step 5: Create a ViewModel that invokes the service call and receives data.

Create a ViewModel named OrdersViewModel that contains an asynchronous method GetData to invoke the service call and store the received data in the proper collection.

public class OrdersViewModel : INotifyPropertyChanged
{
    #region Fields

    WebAPIService webAPIService;
    public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<Order> items;

    #endregion

    #region Properties
    public ObservableCollection<Order> Items
    {
        get
        {
            return items;
        }
        set
        {
            items = value;
            RaisepropertyChanged("Items");
        }
    }
    #endregion

    #region Constructor
    public OrdersViewModel()
    {
        webAPIService = new WebAPIService();
        //Item source that needs to be displayed on the list view.
        items = new ObservableCollection<Order>();
        GetData();
    }
    #endregion

    #region Methods 
    async void GetData()
    {
        Items = await webAPIService.RefreshDataAsync();
    }
    void RaisepropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

Step 6: Add references and utilize the collection of items bindable controls to consume and display the received data.

Here, add references to the Syncfusion ListView control for demo purposes. It can receive the collection of items and display them with a custom data template.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SfListViewSample"
             xmlns:syncfusion="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"
             x:Class="SfListViewSample.MainPage" Padding="10">
    <ContentPage.BindingContext>
        <local:OrdersViewModel x:Name="viewmodel"/>
    </ContentPage.BindingContext>

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Label Text="Fetched data from REST Api" BackgroundColor="SlateBlue" FontSize="18" FontAttributes="Bold" TextColor="White" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
        <syncfusion:SfListView x:Name="listView" ItemSize="90" ItemSpacing="5" Grid.Row="1"
                               BackgroundColor="AliceBlue" ItemsSource="{Binding Items}">
            <syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Frame BorderColor="#757575" Padding="5">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>
                            <Label Grid.Row="0" Grid.Column="0" Text="Order ID  " HorizontalOptions="Start" TextColor="Black" FontSize="16" FontAttributes="Bold"/>
                            <Label Grid.Row="1" Grid.Column="0" Text="Customer ID  " HorizontalOptions="Start" TextColor="Black" FontSize="16" FontAttributes="Bold"/>
                            <Label Grid.Row="2" Grid.Column="0" Text="Ship Country  " HorizontalOptions="Start" TextColor="Black" FontSize="16" FontAttributes="Bold"/>

                            <Label Grid.Row="0" Grid.Column="1" Text="{Binding OrderID}" HorizontalOptions="Start" TextColor="Black" FontSize="16" WidthRequest="100"/>
                            <Label Grid.Row="1" Grid.Column="1" Text="{Binding CustomerID}" HorizontalOptions="Start" TextColor="Black" WidthRequest="100"/>
                            <Label Grid.Row="2" Grid.Column="1" Text="{Binding ShipCountry}" HorizontalOptions="Start" TextColor="Black" WidthRequest="100"/>
                        </Grid>
                    </Frame>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
        </syncfusion:SfListView>

    </Grid>
</ContentPage>

OutputData consumed using ASP.NET Core web API displayed in Xamarin application

Conclusion

I hope this blog guided you through consuming the ASP.NET Core web API in a Xamarin.Forms application. Follow these steps and share your feedback as comments in this blog.

For better understanding, we have shared the sample project at this GitHub location.

Tags:

Share this post:

Comments (4)

Thanks ,That what i was looking for three days ago,You really made my day.

[…] 6 Steps to Consume ASP.NET Core Web API in Xamarin Applications (Magesh Yadav Munuswamy) […]

Thank you for Sharing, This blog is very great and useful.

How to create a helper class ?

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed