Files
2025-07-12 10:50:44 +03:00

65 lines
2.1 KiB
C#

using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
namespace Server;
public abstract class Route
{
public static readonly string connectionString =
"server=127.0.0.1;uid=monty;pwd=some_pass;database=devcon";
public static void SendError(HttpListenerResponse response, Exception ex)
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
string errorMessage = $"Error: {ex.Message}";
byte[] buffer = Encoding.UTF8.GetBytes(errorMessage);
response.ContentType = "text/plain";
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
}
public static void SendSuccess(HttpListenerResponse response)
{
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusDescription = "Status OK";
response.Close();
}
public static void SendSuccess(HttpListenerResponse response, string jsonResponse)
{
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusDescription = "Status OK";
byte[] buffer = Encoding.UTF8.GetBytes(jsonResponse);
response.ContentType = "application/json";
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
}
public static bool ValidateDate(string date)
{
Regex regex = new(@"^\d{4}-\d{2}-\d{2}$");
return regex.IsMatch(date);
}
protected static Dictionary<string, string> ExtractBody(
HttpListenerRequest request,
List<string> allowedParams
)
{
using StreamReader bodyReader = new(request.InputStream, request.ContentEncoding);
JObject bodyJO = JObject.Parse(bodyReader.ReadToEnd());
Dictionary<string, string> bodyParamValues = [];
foreach (var prop in bodyJO.Properties())
{
if (allowedParams.Contains(prop.Name))
bodyParamValues[prop.Name] = prop.Value.ToString();
}
return bodyParamValues;
}
}