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를 설치후 API 호출 테스트
아래와 같이 메소드방식과 RawURL 을 출력
아무것도 하지않고 요청을 받기만 하도록 되어있으므로 원하는 메소드 및 리턴을 정하여 넘겨주도록 한다.
아래글 참조하여 예제 코드 작성하였습니다.
출처: https://manniz.tistory.com/entry/C-CSharp-10분만에-rest-api-server-만들기-rest-api-server-example?category=995582 [Manniz's LIFE:티스토리]
'C# .Net' 카테고리의 다른 글
TCP/IP 통신 Server 및 Client 예제 in C# (Winform) (0) | 2022.09.20 |
---|---|
A, B, C, D, ... Z, AA, AB, AC, ... AZ, BA, BB, ... ZZ, AAA, AAB... 등 알파벳 이름 자동 생성 in C# (Excel 방식) 예제 (0) | 2022.09.14 |
Json / Xml to DataSet (0) | 2022.02.25 |
.Net C/C++/C# Stack Size 변경 방법 (0) | 2021.11.17 |