.NET MAUI - HttpClient 를 이용한 Rest Api 호출
2022. 8. 31. 00:00ㆍMAUI
반응형
MAUI 로 작업을 하다보면 UI 관련 로직은 MAUI로 작성하게 되지만
Business 관련 로직은 MAUI 에서 처리 하기 보다 외부에 노출된 API 서비스를 이용하게 된다.
그래서 이번 시간에 .NET MAUI 에서 외부 API 를 호출 하는 방법에 대해 알아보겠다.
RestAPI/MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.RestAPI.MainPage"
xmlns:local="clr-namespace:MauiApp1.RestAPI"
x:DataType="local:MainViewModel"
Title="Call Rest API">
<VerticalStackLayout>
<Label Text="{Binding Message, Mode=OneWay}"/>
<Button
Text="Change message"
Command="{Binding CallAPICommand}"/>
<CollectionView ItemsSource="{Binding UserModels}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="local:UserModel">
<Grid ColumnDefinitions="*,2*,2*,2*,2*,3*" Padding="10,0,10,0">
<Label Text="{Binding Id}" FontAttributes="Bold" />
<Label Grid.Column="1" Text="{Binding FirstName}" />
<Label Grid.Column="2" Text="{Binding LastName}" />
<Label Grid.Column="3" Text="{Binding Email}" />
<Label Grid.Column="4" Text="{Binding Gender}" />
<Label Grid.Column="5" Text="{Binding IpAddress}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>
RestAPI/MainPage.xaml.cs
using MauiApp1.InjectableServices;
namespace MauiApp1.RestAPI;
public partial class MainPage : ContentPage, ITransientService
{
public MainPage(MainViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
}
MainViewMode.cs
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiApp1.InjectableServices;
using System.Collections.ObjectModel;
namespace MauiApp1.RestAPI;
public partial class MainViewModel : ObservableObject, ITransientService
{
public MainViewModel(IUserService userService)
{
_service = userService;
UserModels ??= new ObservableCollection<UserModel>();
}
[ObservableProperty]
private int _counter;
[ObservableProperty]
private string _message;
private readonly IUserService _service;
[RelayCommand]
private void IncrementCounter() => Counter++;
[RelayCommand]
private async void CallAPI()
{
Message = await _service.Execute();
var users = System.Text.Json.JsonSerializer.Deserialize<List<User>>(Message);
foreach (var user in users)
{
UserModels.Add(new UserModel
{
id = user.id,
firstName = user.first_name,
lastName = user.last_name,
email = user.email,
gender = user.gender,
ipAddress = user.ip_address,
});
}
}
public ObservableCollection<UserModel> UserModels
{
get;
set;
}
}
public partial class UserModel : ObservableObject
{
[ObservableProperty]
public int id;
[ObservableProperty]
public string firstName;
[ObservableProperty]
public string lastName;
[ObservableProperty]
public string email;
[ObservableProperty]
public string gender;
[ObservableProperty]
public string ipAddress;
}
UserService.cs
using MauiApp1.InjectableServices;
namespace MauiApp1.RestAPI;
public interface IUserService : ITransientService
{
Task<string> Execute();
}
public class UserService : IUserService
{
public async Task<string> Execute()
{
using HttpClient httpClient = new HttpClient();
var response = await httpClient
.GetAsync("https://my.api.mockaroo.com/users.json?key=8d630ff0");
return await response.Content.ReadAsStringAsync();
}
}
public class User
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public string gender { get; set; }
public string ip_address { get; set; }
}
UserService 를 보면 HttpClient 를 직접 new 를 통해 생성하여
mockaroo 라는 mock site 를 통해서 json data 를 가져오고 있다.
data 는 아래와ㅏ 같다.
[
{
"id":1,
"first_name":"Sayers",
"last_name":"Vanyashin",
"email":"svanyashin0@google.it",
"gender":
"Male",
"ip_address":"210.36.192.27"
},
...
]
실행
관련영상
반응형
'MAUI' 카테고리의 다른 글
.NET MAUI - Xunit 을 이용한 UnitTest (0) | 2022.09.02 |
---|---|
.NET MAUI - MediatR 을 이용한 Event Mechanism 구현 (0) | 2022.09.01 |
.NET MAUI - Configuration 을 이용한 json 파일 제어 (0) | 2022.08.30 |
.NET MAUI - CommunityToolkit.Maui 유용한 Behavior 3 (0) | 2022.08.26 |
.NET MAUI - CommunityToolkit.Maui 유용한 Behavior 2 (0) | 2022.08.25 |