반응형
// http://localhost:8080/getPersonHandler/333
using System;
using System.IO;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Linq;
namespace RestApiServer
{
internal class Mapping : Attribute
{
public string Map;
public Mapping(string s)
{
Map = s;
}
}
public partial class MainWindow : Window
{
private HttpListener _httpListener;
public MainWindow()
{
InitializeComponent();
}
private void btnServiceStart_Click(object sender, RoutedEventArgs e)
{
InitServer();
}
private void InitServer()
{
if (_httpListener == null)
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(string.Format("http://+:9000/"));
StartServer();
}
}
[Mapping("Person")]
public void GetPersonHandler(int id)
{
this.Dispatcher.Invoke(new Action(() =>
{
txtLog.Text = $"GetPersonHandler : {id}";
}));
}
private void StartServer()
{
if (!_httpListener.IsListening)
{
_httpListener.Start();
txtLog.Text = "Server is started";
Task.Factory.StartNew(() =>
{
while (_httpListener != null)
{
HttpListenerContext context = this._httpListener.GetContext();
string methodName = context.Request.Url.Segments[1].Replace("/", "");
string[] strParams = context.Request.Url
.Segments
.Skip(2)
.Select(s => s.Replace("/", ""))
.ToArray();
var method = this.GetType()
.GetMethods()
.Where(mi => mi.GetCustomAttributes(true).Any(attr => attr is Mapping && ((Mapping)attr).Map == methodName))
.First();
object[] @params = method.GetParameters()
.Select((p, i) => Convert.ChangeType(strParams[i], p.ParameterType))
.ToArray();
object ret = method.Invoke(this, @params);
string retstr = JsonConvert.SerializeObject(ret);
context.Response.Close();
}
});
}
}
}
}
참고 : https://stackoverflow.com/questions/10017564/url-mapping-with-c-sharp-httplistener
반응형
'[====== Development ======] > C#' 카테고리의 다른 글
C# Window Handle 값이 유효한지 확인하는 방법 (1) | 2024.01.04 |
---|---|
grpc - client timeout 설정 (1) | 2024.01.03 |
Enum Type Extentions (4) | 2023.12.05 |
postgeSQL with .Net data Type (0) | 2023.11.28 |
C# gRPC 의 stream Cancel 방법 (0) | 2023.09.08 |