반응형
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. 아래와 같이 테스트명령을 송부 할 수 있습니다.
반응형
'Development > Visual C#' 카테고리의 다른 글
System.Runtime.InteropServices.COMException (0x80040154): 클래스가 등록되지 않았습니다. (예외가 발생한 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)) (0) | 2023.07.06 |
---|---|
[C#] Excel 생성/읽기 데이터 저장하기 (1) | 2022.10.05 |
[C#] EventHandler 이벤트 핸들러 만들기 (1) | 2022.09.21 |
[C#] Kiwoom 로그인 수동 제어 (0) | 2022.09.13 |
[C#] Thread 생성 하기 (0) | 2021.07.16 |
댓글