본문 바로가기

C# .Net

RESTful API Server 구현 예제 in C#

REST API 요청을 받기위한 매우 간단한 Winform 예제

 

코드

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace restAPI_Server
{
    public partial class Form1 : Form
    {
        HttpListener httpListener;
        bool isRunning = false;

        public Form1()
        {
            InitializeComponent();

            ServerInit();
        }

        private void btnServerExecute_Click(object sender, EventArgs e)
        {
            ServerStart();
        }

        private void btnServerStop_Click(object sender, EventArgs e)
        {
            ServerStop();
        }

        private void ServerInit()
        {
            string address = "http://+:8686/";

            if (httpListener == null)
            {
                httpListener = new HttpListener();
                httpListener.Prefixes.Add(string.Format(address));
            }
        }

        private void ServerStart()
        {
            if (!httpListener.IsListening && !isRunning)
            {
                // Listener 실행
                httpListener.Start(); // 엑세스 거부 오류 - 관리자권한 필요
                isRunning = true;
                richTextBox1.Text = "Server is started\r\n";
                
                Task.Factory.StartNew(() =>
                {
                    while (httpListener != null && isRunning)
                    {
                        string result = "";
                        try
                        {
                            // 받은 요청
                            HttpListenerContext context = this.httpListener.GetContext();

                            string rawUrl = context.Request.RawUrl;
                            string httpMethod = context.Request.HttpMethod;

                            result += string.Format("HttpMethod = {0}\r\n", httpMethod);
                            result += string.Format("RawUrl = {0}\r\n", rawUrl);

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

                            // 응답 설정
                            //context.Response.StatusCode = 500;
                            context.Response.Close();
                        }
                        catch (HttpListenerException ex)
                        {
                            result += string.Format("HttpListener Error: {0}\r\n", ex.Message);
                        }
                    }
                });

            }
        }
        private void ServerStop()
        {
            if (httpListener.IsListening && isRunning)
            {
                httpListener.Stop();
                isRunning = false;
                richTextBox1.Text += "Server is stoped\r\n";
            }
        }
    }
}

 

 

디버깅시 엑세스 권한 오류가 발생하면 VisualStudio를 관리자권한으로 실행하면 해결.

 

 

서버실행

 

Talend API Tester (크롬 확장프로그램)

크롬 확장프로그램인 Talend API Tester를 설치후 API 호출 테스트

 

아래와 같이 메소드방식과 RawURL 을 출력

 

서버 중단

 

아무것도 하지않고 요청을 받기만 하도록 되어있으므로 원하는 메소드 및 리턴을 정하여 넘겨주도록 한다.

 

 

 

 

아래글 참조하여 예제 코드 작성하였습니다.

 

출처: https://manniz.tistory.com/entry/C-CSharp-10분만에-rest-api-server-만들기-rest-api-server-example?category=995582 [Manniz's LIFE:티스토리]