Visual Studio for mac을 사용하는 Xamarin Forms 4.2 교재 업데이트를 하고 있습니다. Azure에 올려두는 REST API가 수정되었습니다.

in #kr5 years ago (edited)

가을과 겨울에 오픈될 자마린 과정을 위해 오랜만에 교재를 업데이트하고 있습니다. REST Api를 사용하는 코드로 수정을 하고 있는데 Azure에 추가하는 서버측 코드가 재미있게 공개되어 있는 예제가 있어서 링크를 걸어 둡니다.

https://docs.microsoft.com/ko-kr/learn/modules/consume-rest-services/4-exercise-consume-rest-service-with-httpclient

위의 링크에서 제공된 것처럼 아래와 같이 그대로 copy & paste하면 Web App이 Azure에 생성됩니다.

정리하면 아래와 같습니다.

REST 서비스 코드의 위치를 저장할 gitrepo라는 변수를 정의합니다. 리포지토리에 대한 URL은 https://github.com/MicrosoftDocs/mslearn-xamarin-consume-rest-services입니다.

gitrepo=https://github.com/MicrosoftDocs/mslearn-xamarin-consume-rest-services

BookServer 프로젝트 파일의 위치를 저장할 gitpath라는 변수를 정의합니다. 경로는 src/webservice/BookServer/BookServer.csproj입니다.

gitpath=src/webservice/BookServer/BookServer.csproj

웹앱의 이름을 저장하기 위해 webappname이라는 변수를 정의합니다. 값을 bookserver$RANDOM으로 설정합니다.

webappname=bookserver$RANDOM

표준 계층에서 Azure App Service 계획을 만듭니다.

az appservice plan create --name $webappname --resource-group Learn-864eafb8-42c9-4901-a5ec-1ee08b6d3992 --sku FREE

REST 서비스를 호스트할 웹앱을 만듭니다.

az webapp create --name $webappname --resource-group Learn-864eafb8-42c9-4901-a5ec-1ee08b6d3992 --plan $webappname

애플리케이션 설정에 프로젝트 파일 경로를 추가합니다.

az webapp config appsettings set -g Learn-864eafb8-42c9-4901-a5ec-1ee08b6d3992 -n $webappname --settings PROJECT=$gitpath

GitHub에서 REST 서비스를 배포합니다.

az webapp deployment source config --name $webappname --resource-group Learn-864eafb8-42c9-4901-a5ec-1ee08b6d3992 --repo-url $gitrepo --branch master --manual-integration

다음 명령의 결과를 저장합니다. 나중에 Xamarin.Forms 애플리케이션에서 해당 결과를 사용하여 REST 서비스에 연결합니다.

echo https://$webappname.azurewebsites.net

참조는 아래와 같이 한다. 공통 프로젝트에는 Microsoft.Net.Http, Json.net을 해준다.
스크린샷 2019-09-11 오후 1.24.25.png

각 프로젝트 마다 Json.net을 추가한다.
스크린샷 2019-09-11 오후 1.24.37.png

스크린샷 2019-09-11 오후 1.24.42.png

제가 업로드한 주소는 다음과 같습니다.

https://bookserver22542.azurewebsites.net

자마린용 클라이언트를 받아서 아래와 같이 코드를 수정하면 됩니다.

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

namespace BookClient.Data
{
    public class BookManager
    {
        //아래의 주소를 변경해서 연결하면 된다. 복사한 주소에 + /api/books/ 
        const string Url = " https://bookserver22542.azurewebsites.net/api/books/";
        private string authorizationKey;

        private async Task<HttpClient> GetClient()
        {
            HttpClient client = new HttpClient();
            if (string.IsNullOrEmpty(authorizationKey))
            {
                authorizationKey = await client.GetStringAsync(Url + "login");
                authorizationKey = JsonConvert.DeserializeObject<string>(authorizationKey);
            }

            client.DefaultRequestHeaders.Add("Authorization", authorizationKey);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            return client;
        }

        public async Task<IEnumerable<Book>> GetAll()
        {
            HttpClient client = await GetClient();
            string result = await client.GetStringAsync(Url);
            return JsonConvert.DeserializeObject<IEnumerable<Book>>(result);
        }

        public async Task<Book> Add(string title, string author, string genre)
        {
            Book book = new Book()
            {
                Title = title,
                Authors = new List<string>(new[] { author }),
                ISBN = string.Empty,
                Genre = genre,
                PublishDate = DateTime.Now.Date,
            };

            HttpClient client = await GetClient();
            var response = await client.PostAsync(Url,
                new StringContent(
                    JsonConvert.SerializeObject(book),
                    Encoding.UTF8, "application/json"));

            return JsonConvert.DeserializeObject<Book>(
                await response.Content.ReadAsStringAsync());
        }

        public async Task Update(Book book)
        {
            HttpClient client = await GetClient();
            await client.PutAsync(Url + "/" + book.ISBN,
                new StringContent(
                    JsonConvert.SerializeObject(book),
                    Encoding.UTF8, "application/json"));
        }

        public async Task Delete(string isbn)
        {
            HttpClient client = await GetClient();
            await client.DeleteAsync(Url + isbn);
        }
    }
}

각각 아이폰과 안드로이드폰에서 실행된 예제 화면입니다.

스크린샷 2019-09-11 오후 1.24.08.png

스크린샷 2019-09-11 오후 1.26.15.png

Coin Marketplace

STEEM 0.18
TRX 0.14
JST 0.030
BTC 58659.71
ETH 3164.52
USDT 1.00
SBD 2.43