본문 바로가기
Blazor

Blazor WASM] REST API, API로 리스트 가져와서 뿌려주기

by Fastlane 2021. 9. 16.
728x90
반응형

소스링크 : https://github.com/BigExecution/BlazorWASM.git

 

open api를 호출해서 대학정보를 가져와 리스트로 뿌려주자

1. 우선 Model을 만들자. 

Models 폴더를 추가 -> University class를 추가한다. 

2. 그 다음, REST API 호출 함수를 관리할 Service를 만들자. 

Services 폴더 추가 

BaseService 클래스(BaseService.cs) 추가 

UniversityService클래스(GitService.cs) 추가 

IUniversityService인터페이스(IUniversityService.cs) 추가

BaseService 클래스에는 Get, Post 호출시 사용할 Generic을 활용한 공통함수가 들어있다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

namespace TEST.Services
{
	public class BaseService
	{
		private readonly HttpClient _httpClient;

		public BaseService(HttpClient httpClient)
		{
			_httpClient = httpClient;
		}



		public async Task<IEnumerable<TResult>> GetMethodList<TResult>(string url)
		{

			try
			{
				HttpResponseMessage response = await _httpClient.GetAsync(url);
				response.EnsureSuccessStatusCode();
				if (response.StatusCode == System.Net.HttpStatusCode.OK)
				{

					using var responseStream = await response.Content.ReadAsStreamAsync();
					return await JsonSerializer.DeserializeAsync
							<IEnumerable<TResult>>(responseStream);
				}

				return null;

			}
			catch (HttpRequestException e)
			{
				return null;
			}
		}

		public async Task<TResult> GetMethod<TResult>(string url)
		{

			try
			{
				HttpResponseMessage response = await _httpClient.GetAsync(url);
				response.EnsureSuccessStatusCode();
				if (response.StatusCode == System.Net.HttpStatusCode.OK)
				{

					using var responseStream = await response.Content.ReadAsStreamAsync();
					return await JsonSerializer.DeserializeAsync
							<TResult>(responseStream);
				}

				return default(TResult);

			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				return default(TResult);
			}
		}

		public async Task PostMethodList<T>(string url, List<T> content)
		{
			await _httpClient.PostAsJsonAsync(url, content);
		}

		public async Task PostMethod<T>(string url, T content)
		{
			await _httpClient.PostAsJsonAsync(url, content);
		}

		public async Task<TResult> PostMethodGetObject<TResult, TValue>(string url, TValue content)
		{
			try
			{
				HttpResponseMessage response = await _httpClient.PostAsJsonAsync(url, content);
				response.EnsureSuccessStatusCode();
				if (response.StatusCode == System.Net.HttpStatusCode.OK)
				{
					using var responseStream = await response.Content.ReadAsStreamAsync();
					return await JsonSerializer.DeserializeAsync
							<TResult>(responseStream);
				}
				return default(TResult);
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				return default(TResult);
			}
		}
	}
}

IUniversityService.cs 인터페이스에 대학 리스트를 가져올 함수를 추가한다. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TEST.Models;

namespace TEST.Services
{
    public interface IUniversityService
    {
        Task<IEnumerable<University>> GetUniversities();
    }
}

UniversityService.cs에서 BaseService와 IUniversityService를 상속받고 함수를 구현한다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using TEST.Models;

namespace TEST.Services
{
    public class UniversityService : BaseService, IUniversityService
    {
        public UniversityService(HttpClient httpClient) : base(httpClient) { }

        public async Task<IEnumerable<University>> GetUniversities()
        {
            return await GetMethodList<University>($"search?country=Korea,+Republic+of");
        }
    }
}

3. Program.cs 파일에 IHttpClientFactory 인터페이스의 AddHttpClient를 사용하여 Service를 Service Collections에 추가하고 HttlClient를 구성한다.

Microsoft.Extensions.Http 패키지를 설치한다. 

Install-Package Microsoft.Extensions.Http -Version 5.0.0

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using TEST.Services;

namespace TEST
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            //builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            builder.Services.AddHttpClient<IUniversityService, UniversityService>(client =>
            {
                client.BaseAddress = new Uri("http://universities.hipolabs.com");
            });

            await builder.Build().RunAsync();
        }
    }
}

4. Razor 페이지를 추가한다. 

UniversityData.razor

@using TEST.Models;
@using TEST.Services;
@page "/universitydata";

<h1>Universities of Korea</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (universities == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var university in universities.ToList())
            {
                <tr>
                    <td>@university.name</td>
                    <td>@university.country</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {


    protected IEnumerable<University> universities;

    [Inject]
    protected IUniversityService UniversityService { get; set; }


    protected override async Task OnInitializedAsync()
    {
        universities = await UniversityService.GetUniversities();
    }
}

5. 서버 실행 후 아래와 같이 확인 가능하다. 

 

728x90
반응형

댓글