Advertisement
QwarkDev

Express Framework in .NET (c#)

Dec 2nd, 2020
1,511
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.15 KB | None | 0 0
  1. // File: Core.cs
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Net;
  7. using System.Text;
  8.  
  9. using static ServiceHandler.Json;
  10.  
  11. namespace ServiceHandler
  12. {
  13.     public class ServiceHandler
  14.     {
  15.         readonly HttpListener listener = new HttpListener();
  16.         readonly List<Callback> callbacks = new List<Callback>();
  17.  
  18.         public LogLevelEnum LogLevel { get; set; }
  19.         public int Port { get; protected set; }
  20.  
  21.         public ServiceHandler(int port)
  22.         {
  23.             Port = port;
  24.         }
  25.  
  26.         public ServiceHandler(int port, LogLevelEnum logLevel)
  27.         {
  28.             Port = port;
  29.             LogLevel = logLevel;
  30.         }
  31.  
  32.         public void Start()
  33.         {
  34.             listener.Start();
  35.  
  36.             if (LogLevel != LogLevelEnum.Nothing)
  37.                 Console.WriteLine($"Сервис запущен! Порт: {Port}");
  38.  
  39.             while (true)
  40.             {
  41.                 var httpContext = listener.GetContext();
  42.                 var context = new Context() { HttpContext = httpContext };
  43.  
  44.                 httpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
  45.                 httpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
  46.                 httpContext.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
  47.  
  48.                 Process(context);
  49.             }
  50.         }
  51.  
  52.         public void Get(string route, Action<Context> action)
  53.         {
  54.             var callback = new Callback()
  55.             {
  56.                 CallbackHandler = this,
  57.                 CallbackAction = action,
  58.                 RequestString = route,
  59.                 CallbackMethod = "GET"
  60.             };
  61.  
  62.             callbacks.Add(callback);
  63.             listener.Prefixes.Add($"http://*:{Port}/{route}/");
  64.              
  65.             if (LogLevel != LogLevelEnum.Nothing)
  66.                 Console.WriteLine($"Новый маршрут: [GET] /{route}/");
  67.         }
  68.  
  69.         public void Post(string route, Action<Context> action)
  70.         {
  71.             var callback = new Callback()
  72.             {
  73.                 CallbackHandler = this,
  74.                 CallbackAction = action,
  75.                 RequestString = route,
  76.                 CallbackMethod = "POST"
  77.             };
  78.  
  79.             callbacks.Add(callback);
  80.             listener.Prefixes.Add($"http://*:{Port}/{route}/");
  81.  
  82.             if (LogLevel != LogLevelEnum.Nothing)
  83.                 Console.WriteLine($"Новый маршрут: [POST] /{route}/");
  84.         }
  85.  
  86.         private string NormalazeUrl(string url)
  87.         {
  88.             return url.Substring(1, url.Length - 1);
  89.         }
  90.  
  91.         protected void Process(Context context)
  92.         {
  93.             var httpContext = context.HttpContext;
  94.             var route = httpContext.Request.RawUrl;
  95.  
  96.             route = NormalazeUrl(route);
  97.  
  98.             foreach (var t in callbacks)
  99.             {
  100.                 if (t.RequestString.ToLower() == route.ToLower() &&
  101.                     t.CallbackMethod.ToLower() == httpContext.Request.HttpMethod.ToLower())
  102.                 {
  103.                     t.CallbackAction?.Invoke(context);
  104.  
  105.                     if (LogLevel != LogLevelEnum.Nothing)
  106.                         Console.WriteLine($"{httpContext.Request.HttpMethod.ToUpper().PadRight(4)} /{route}/");
  107.  
  108.                     return;
  109.                 }
  110.             }
  111.  
  112.             var answer = $"Handler for [{httpContext.Request.HttpMethod.ToUpper()}] /{route}/ not found";
  113.             context.Answer(new Message() { Status = "ERROR", Content = answer }, 400);
  114.  
  115.             if (LogLevel != LogLevelEnum.Nothing)
  116.                 Console.WriteLine(answer);
  117.         }
  118.     }
  119.  
  120.     public enum LogLevelEnum
  121.     {
  122.         Debug,
  123.         Release,
  124.         Nothing
  125.     }
  126.  
  127.     public class Context
  128.     {
  129.         public HttpListenerContext HttpContext { get; set; }
  130.         public string Body { get { return ReadBody(); } }
  131.  
  132.         public void Answer(Message message, int code = 200)
  133.         {
  134.             Answer(ToJson(message), code);
  135.         }
  136.  
  137.         public void Answer(string data, int code = 200)
  138.         {
  139.             try
  140.             {
  141.                 byte[] buffer = Encoding.UTF8.GetBytes(data);
  142.  
  143.                 HttpContext.Response.ContentLength64 = buffer.Length;
  144.                 Stream output = HttpContext.Response.OutputStream;
  145.  
  146.                 HttpContext.Response.StatusCode = code;
  147.                 output.Write(buffer, 0, buffer.Length);
  148.                 output.Close();
  149.             }
  150.             catch (Exception x) { Console.WriteLine(x.ToString()); }
  151.         }
  152.  
  153.         private string ReadBody()
  154.         {
  155.             try
  156.             {
  157.                 var stream = HttpContext.Request.InputStream;
  158.                 using StreamReader reader = new StreamReader(stream);
  159.  
  160.                 return reader.ReadToEnd();
  161.             }
  162.             catch (Exception x) { throw new Exception($"Ошибка чтения тела запроса\nВероятно был вызван метод context.Answer() до попытки чтения\n\n{x}"); }
  163.         }
  164.     }
  165.  
  166.     public class Message
  167.     {
  168.         public string Status { get; set; }
  169.         public string Content { get; set; }
  170.  
  171.         public Message() { Status = "OK"; }
  172.     }
  173.  
  174.     public class Callback
  175.     {
  176.         public ServiceHandler CallbackHandler { get; set; }
  177.         public string RequestString { get; set; }
  178.         public Action<Context> CallbackAction { get; set; }
  179.         public string CallbackMethod { get; set; }
  180.     }
  181. }
  182.  
  183.  
  184. // File: Functions.cs
  185.  
  186. using System;
  187. using System.Linq;
  188. using System.Text.Json;
  189.  
  190. namespace ServiceHandler
  191. {
  192.     public static class Functions
  193.     {
  194.         public static string[] GetArgs(Context context)
  195.         {
  196.             var splited = context.HttpContext.Request.Url.ToString().Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries);
  197.  
  198.             if (splited.Length < 2) return null;
  199.  
  200.             splited = splited[1].Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
  201.             return splited.ToArray();
  202.         }
  203.  
  204.         public static string GetParam(string[] args, string param, string defaultReturn = "")
  205.         {
  206.             if (args is null) return null;
  207.  
  208.             foreach (var t in args)
  209.             {
  210.                 var splited = t.Split('=');
  211.  
  212.                 if (splited.Length < 2) continue;
  213.  
  214.                 if (splited[0].ToLower() == param.ToLower())
  215.                 {
  216.                     return splited[1];
  217.                 }
  218.             }
  219.  
  220.             return defaultReturn;
  221.         }
  222.     }
  223.  
  224.     public static class Json
  225.     {
  226.         public static string ToJson(object obj)
  227.         {
  228.             return JsonSerializer.Serialize(obj);
  229.         }
  230.  
  231.         public static T FromJson<T>(string data)
  232.         {
  233.             return JsonSerializer.Deserialize<T>(data);
  234.         }
  235.     }
  236. }
  237.  
  238.  
  239. // Example of using:
  240.  
  241. var service = new ServiceHandler(1010);
  242.  
  243. service.Get("api", (context) => {
  244.     context.Answer("Hello!");
  245. });
  246.  
  247. service.Post("api/test-body", (context) => {
  248.     context.Answer("Hello! Body: " + context.Body);
  249. });
  250.  
  251. service.Start();
  252.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement