본문 바로가기
Development/Visual C#

[C#] RestFul API 서버 만들기 예제

by qWooWp 2023. 7. 6.
반응형

1. Visual Studio 2019 로 프로젝트를 생성합니다. 

2. 필요에 따른 아래 컴포넌트를 소스 상단에 추가 합니다. 

 

using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.IO;

 

3. 서버 시작을 위한 함수를 선언합니다. 

 

// 관리자 컨솔에서 아래 주소를 등록해야 한다. 
        //netsh http add urlacl url=http://+:8686/ user=everyone
        private void serverInit()
        {
            if (httpListener == null)
            {
                httpListener = new HttpListener();
                httpListener.Prefixes.Add(string.Format("http://+:8686/"));
                serverStart();
            }
        }

        private void serverStart()
        {

            if (!httpListener.IsListening)
            {                
                httpListener.Start();
                richTextBox1.Text = "Server is started";

                Task.Factory.StartNew(() =>
                {
                    while (httpListener != null)
                    {
                        HttpListenerContext context = this.httpListener.GetContext();

                        string rawurl = context.Request.RawUrl;
                        string httpmethod = context.Request.HttpMethod;

                        string result = "";

                        result += string.Format("httpmethod = {0}\r\n", httpmethod);
                        result += string.Format("rawurl = {0}\r\n", rawurl);
                        // 위 2가지 를 베이스로 RestAPI 파서를 구현한다. 
                        // 기능 호출은 POST
                        // 상태 확인은 GET
                        if (context.Request.HttpMethod == HttpMethod.Post.Method)
                        {    
                            // body 데이터를 json 으로 받아서 Parsing 
                            using (var reader = new StreamReader(context.Request.InputStream,
                                     context.Request.ContentEncoding))
                            {
                                result += reader.ReadToEnd();
                            }
                            
                            ;
                            // The action is a post 
                        }else if (context.Request.HttpMethod == HttpMethod.Put.Method)
                        {
                            // The action is a put 
                            ;
                        }else if (context.Request.HttpMethod == HttpMethod.Delete.Method)
                        {
                            // The action is a DELETE
                            ;
                        }else if (context.Request.HttpMethod == HttpMethod.Get.Method)
                        {
                            // The action is a Get
                            ;
                        }

                        if (richTextBox1.InvokeRequired)
                            richTextBox1.Invoke(new MethodInvoker(delegate { richTextBox1.Text = result; }));
                        else
                            richTextBox1.Text = result;

                        context.Response.Close();

                    }
                });

            }
        }

 

* 각 요청에 따른 JSON 파싱 또는 URL 에 따른 기능 구현을 위의 주석 처리한 부분에 추가 하면 됩니다. 

** 중요한것은 대기하려는 주소에 대해서 미리 등록을 해줘야 합니다. 

*** 버튼 또는 서버 시작 또는 원하는 이벤트에서 serverInit() 함수를 호출하면 됩니다. 

 

4. 관리자 컨솔을 열고 아래와 같이 입력하여 사용할 수 있도록 해주어야 합니다. 

>> netsh http add urlacl url=http://+:8686/ user=everyone

 

5. 테스트를 위해 예를들어 Chrome 의 아래 확장팩을 설치하고 테스트를 할 수 있습니다. 

 

1.     Talend API Tester 검색해서 크롬 브라우저에 등록합니다.

A.      아래와 같이 테스트명령을 송부 있습니다.

 

반응형

댓글