본문 바로가기

C# Winform

C# 초간단 Rest API Server 만들기 (Simple-HTTP)

by C기억저장소 2023. 6. 30.

C# Rest API Server 만들기

 

Simple-HTTP 이용하기

 

GitHub - dajuric/simple-http: Simple, portable HTTP server for .NET based on HttpListener.

Simple, portable HTTP server for .NET based on HttpListener. - GitHub - dajuric/simple-http: Simple, portable HTTP server for .NET based on HttpListener.

github.com

 

Simple-HTTP 설치

Nuget에서 검색후 설치

 

2. Route 설정 및 관리

프로젝트에 Service폴더 추가 및 HttpRoute.cs 추가

using SimpleHttp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace SampleCode.Service
{
    public class HttpRoute
    {
        private Thread httpRequst_thread;
        public HttpRoute()
        {
            SetRoutes();

            httpRequst_thread = new Thread(Http_Proc);
            httpRequst_thread.IsBackground = true;
            httpRequst_thread.Start();
        }

        private void SetRoutes()
        {

            Route.Add("/GetTest", (req, res, props) =>
            {
                res.AsText("GetTest");
            });

            Route.Add("/GetTest/TEST1", (req, res, props) => GetTest_TEST1(req, res, props));

            Route.Add("/PostTest", (req, res, props) => PostTest(req, res, props), "POST");
            Route.Add("/PostTest", (req, res, props) => OPTIONS_HeadersProc(res), "OPTIONS");

        }

        private void GetTest_TEST1(HttpListenerRequest req, HttpListenerResponse res, Dictionary<string, string> props)
        {
            try
            {
                res.Headers.Add("Access-Control-Allow-Origin", "*");
                res.AsText("GetTest_TEST1");
            }
            catch (Exception e)
            {
                res.Headers.Add("Access-Control-Allow-Origin", "*");
                res.AsText("ERROR");
            }
        }

        private void PostTest(HttpListenerRequest req, HttpListenerResponse res, Dictionary<string, string> props)
        {
            try
            {
                //Console.WriteLine("broadcast_signal - " + req.HasEntityBody);
                if (req.HasEntityBody)
                {
                    using (System.IO.Stream body = req.InputStream) // here we have data
                    {
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(body, req.ContentEncoding))
                        {
                            string order = reader.ReadToEnd();
                            Console.WriteLine(order);
                            POST_HeadersProc(res, order);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                POST_HeadersProc(res, "Exception");
            }
        }

        private void POST_HeadersProc(HttpListenerResponse res, string data)
        {
            res.Headers.Add("Access-Control-Allow-Origin", "*");
            res.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
            res.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With");
            res.AsText(data);
        }

        private void OPTIONS_HeadersProc(HttpListenerResponse res)
        {
            POST_HeadersProc(res, "");
        }

        private void Http_Proc()
        {
            try
            {
                //HttpServer.ListenAsync(8080, CancellationToken.None, Route.OnHttpRequestAsync).Wait();
                HttpServer.ListenAsync(1337, CancellationToken.None, Route.OnHttpRequestAsync).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Http_Proc - Exception!!!!");
                Console.WriteLine(ex.Message);
            }
        }
    }
}

 

HttpRoute 시작

메인 From에 버튼을 추가하고 HttpRoute 시작

using SampleCode.Service;

private void btnRestApiStart_Click(object sender, EventArgs e)
{
    HttpRoute httpRoute = new HttpRoute();
}

 

결과 확인

/GetTest 확인

/GetTest/TEST1 확인