새소식

Program Language/📓 C#

[5분 내로] C# httpListener를 사용하여 REST API 서버 구축하기

  • -
728x90

안녕하세요. 팀드모네입니다.

C# httpListener를 사용하여 REST API 서버 구축하는 방법을 공유드립니다.

 

AJAX를 통해 데이터를 전송하고

C# 서버 (httpListener)를 통해 데이터를 받은 후

잘 되었으면 success를 회신하는 A부터 Z급 예제입니다.

 

이 포스팅은 계속 업데이트 예정입니다!

로이 필딩이 언급하였던 것처럼, REST 규칙을 다 지켜야 RESTful API겠죠? (ㅠㅠㅠㅠ)

따라서, 포스팅 제목은 어그로..!!

 

무튼 JSONP를 사용하지 않도록, CORS 문제도 해결해뒀습니다.

nuget으로 받기 편하시게, using 남겨드립니다.

한글이 깨지지 않도록 인코딩 처리도 했습니다 :)

 

0. AJAX 요청

var data= {
    "id":"han",
    "name" : "hoon"
}

$.ajax({
    type: "POST",
    crossdomain: true,
    accept: "application/json",
    contentType: "application/json; charset=utf-8",
	url : url,
	data : JSON.stringify(data),
	dataType : "json",
	success : function(data) {
		console.log('성공 - ', data);
	},
	error : function(e) {
		console.log('실패 - ', e);
	}
});

 

1. C# httpListener server 소스코드

using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

private void serverStart()
{

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

        Task.Factory.StartNew(() =>
        {
            while (httpListener != null)
            {

                HttpListenerContext context = this.httpListener.GetContext();
                HttpListenerResponse response = context.Response;
                HttpListenerRequest request = context.Request;
                
                string jsonData = ShowRequestData(context.Request);
                string jsonString = "";
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes("false");
                
                try
                {
                    jsonString = CheckDetails("success");
                    buffer = System.Text.Encoding.UTF8.GetBytes(jsonString);
                    response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                    response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    response.AddHeader("Access-Control-Max-Age", "1728000");
                    response.AppendHeader("Access-Control-Allow-Origin", "*");
                    response.StatusCode = 200;
                    response.ContentLength64 = buffer.Length;
                    Stream outputStream = response.OutputStream;
                    outputStream.Write(buffer, 0, buffer.Length);
                    outputStream.Close();
                }
                catch
                {
                    jsonString = CheckDetails("fail");
                    buffer = System.Text.Encoding.UTF8.GetBytes(jsonString);
                    response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                    response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    response.AddHeader("Access-Control-Max-Age", "1728000");
                    response.AppendHeader("Access-Control-Allow-Origin", "*");
                    response.StatusCode = 500;

                    response.ContentLength64 = buffer.Length;
                    Stream outputStream = response.OutputStream;
                    outputStream.Write(buffer, 0, buffer.Length);
                    outputStream.Close();
                }

                context.Response.Close();
            }
        });
    }
}

 

2. C# 따로 작성한 메서드

public static String ShowRequestData (HttpListenerRequest request)
{
    if (!request.HasEntityBody)
    {
        Console.WriteLine("No client data was sent with the request.");
        return "";
    }
    
    System.IO.Stream body = request.InputStream;
    System.Text.Encoding encoding = Encoding.UTF8;
    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);

    // Convert the data to a string and display it on the console.
    string jsonData = reader.ReadToEnd();
    Console.WriteLine("jsonData : " +jsonData);
    Console.WriteLine("End of client data:");
    body.Close();
    reader.Close();
    return jsonData;
}

public string CheckDetails(string param1)
{
    var chk = new check
    {
        result = param1
    };
    return JsonConvert.SerializeObject(chk);
}

 public class check
{
    public string result { get; set; }
}

 

3. 작업 결과

급하게 작업한거라 소스가 좀 지져분한 것 같네요 ㅠ

그래도 없는 것 보단 좋겠죠? 도움이 되길 바랍니다.

코드 개선점이나.. 잘 안되는 부분이 있다면 댓글 남겨주세요.

좋은 하루 보내세요~

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.