Simplified project struct naming. Cleaned up code and added missing documentation. Routes now use a RouteContext to allow extensions and future modules.

This commit is contained in:
2022-02-06 21:14:36 -08:00
parent 87a9b961bd
commit ccad0dd66d
19 changed files with 353 additions and 94 deletions

25
Rest.Net/Rest.Net.sln Normal file
View File

@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32112.339
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rest.Net", "Rest.Net\Rest.Net.csproj", "{C885E940-05C8-43BB-B80B-02F6AAF1AE09}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C885E940-05C8-43BB-B80B-02F6AAF1AE09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C885E940-05C8-43BB-B80B-02F6AAF1AE09}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C885E940-05C8-43BB-B80B-02F6AAF1AE09}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C885E940-05C8-43BB-B80B-02F6AAF1AE09}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D951ABAA-266B-4E0D-9E11-E6ABD08C8BAB}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// A set of extensions to help with HttpListenerRequests.
/// </summary>
public static class HttpListenerRequestExtensions
{
/// <summary>
/// Reads the content of a HttpListenerRequest as a string and returns it.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static string ReadAsString(this HttpListenerRequest request)
{
try
{
using (var input = request.InputStream)
using (var stream = new StreamReader(input))
return stream.ReadToEnd();
}
catch
{
return "";
}
}
/// <summary>
/// Reads the content of a HttpListenerRequest as a json object and returns it.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request"></param>
/// <returns></returns>
public static T ReadAsJson<T>(this HttpListenerRequest request)
{
try
{
using (var input = request.InputStream)
using (var stream = new StreamReader(input))
return JsonConvert.DeserializeObject<T>(stream.ReadToEnd());
}
catch
{
return default(T);
}
}
}
}

View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// A set of extensions to help with HttpListenerResponses.
/// </summary>
public static class HttpListenerResponseExtensions
{
/// <summary>
/// Sets the response content type to text and writes the given text to it.
/// </summary>
/// <param name="response"></param>
/// <param name="text"></param>
/// <returns></returns>
public static HttpListenerResponse WithText(this HttpListenerResponse response, string text)
{
response.ContentType = "text/plain";
var bytes = Encoding.Unicode.GetBytes(text);
response.OutputStream.Write(bytes, 0, bytes.Length);
return response;
}
/// <summary>
/// Sets the response content type to json and serializes the object as json and writes it.
/// </summary>
/// <param name="response"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static HttpListenerResponse WithJson(this HttpListenerResponse response, object obj)
{
response.ContentType = "application/json";
var bytes = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(obj));
response.OutputStream.Write(bytes, 0, bytes.Length);
return response;
}
/// <summary>
/// Sets the response content type to a file and writes the given file content to the response.
/// </summary>
/// <param name="response"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public static HttpListenerResponse WithFile(this HttpListenerResponse response, string filePath)
{
response.ContentType = "application/octet-stream";
response.Headers.Add("Content-Deposition", $@"attachment; filename=""{Path.GetFileName(filePath)}""");
response.SendChunked = true;
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var responseStream = response.OutputStream)
fileStream.CopyTo(responseStream);
return response;
}
/// <summary>
/// Sets the status code for a given response.
/// </summary>
/// <param name="response"></param>
/// <param name="status"></param>
/// <returns></returns>
public static HttpListenerResponse WithStatus(this HttpListenerResponse response, HttpStatusCode status)
{
try
{
response.StatusCode = (int)status;
return response;
}
catch
{
return response;
}
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MontoyaTech.Rest.Net
{
internal static class StringExtensions
{
public static int Count(this string input, char c)
{
int count = 0;
int len = input.Length;
for (int i = 0; i < len; i++)
if (input[i] == c)
count++;
return count;
}
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// An enum containing the available http request methods.
///
/// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
/// </summary>
public enum HttpRequestMethod
{
Get,
Head,
Post,
Put,
Delete,
Connect,
Options,
Trace,
Patch
}
}

View File

@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>library</OutputType>
<TargetFramework>net472</TargetFramework>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Authors>MontoyaTech</Authors>
<Company>MontoyaTech</Company>
<Copyright>MontoyaTech 2022</Copyright>
<PackageProjectUrl>https://code.montoyatech.com/MontoyaTech/Rest.Net</PackageProjectUrl>
<Description>A simple C# library for creating a rest api.</Description>
<PackageTags>MontoyaTech;Rest.Net</PackageTags>
<NeutralLanguage>en</NeutralLanguage>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<AssemblyName>MontoyaTech.Rest.Net</AssemblyName>
<RootNamespace>MontoyaTech.Rest.Net</RootNamespace>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Version>1.0.*</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json">
<Version>13.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>library</OutputType>
<TargetFramework>net472</TargetFramework>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Authors>MontoyaTech</Authors>
<Company>MontoyaTech</Company>
<Copyright>MontoyaTech 2022</Copyright>
<PackageProjectUrl>https://code.montoyatech.com/MontoyaTech/Rest.Net</PackageProjectUrl>
<Description>A simple C# library for creating a rest api.</Description>
<PackageTags>MontoyaTech;Rest.Net</PackageTags>
<NeutralLanguage>en</NeutralLanguage>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<AssemblyName>MontoyaTech.Rest.Net</AssemblyName>
<RootNamespace>MontoyaTech.Rest.Net</RootNamespace>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Version>1.0.1</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json">
<Version>13.0.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
</Project>

289
Rest.Net/Rest.Net/Route.cs Normal file
View File

@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// The outline of a Http Route.
/// </summary>
public class Route
{
/// <summary>
/// The http method for this route.
/// </summary>
public string Method;
/// <summary>
/// The syntax of this route.
/// </summary>
public string Syntax;
/// <summary>
/// The target function to invoke if this route is invoked.
/// </summary>
private Func<RouteContext, HttpListenerResponse> Target;
/// <summary>
/// Whether or not to close the response after the route is invoked.
/// </summary>
public bool CloseResponse = true;
internal Route() { }
/// <summary>
/// Creates a new route with a given method, syntax, target and optional close response flag.
/// </summary>
/// <param name="method"></param>
/// <param name="syntax"></param>
/// <param name="target"></param>
/// <param name="closeResponse"></param>
public Route(string method, string syntax, Func<RouteContext, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
/// <summary>
/// Creates a new route with a given method, syntax, target and optional close response flag.
/// </summary>
/// <param name="method"></param>
/// <param name="syntax"></param>
/// <param name="target"></param>
/// <param name="closeResponse"></param>
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
/// <summary>
/// Invokes this route with a context and a given set of string arguments.
/// </summary>
/// <param name="context"></param>
/// <param name="arguments"></param>
public virtual void Invoke(RouteContext context, params string[] arguments)
{
this.Target.Invoke(context);
}
}
public class Route<T1> : Route
{
private Func<RouteContext, T1, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(context, RouteArgumentConverter.Convert<T1>(arguments[0]));
}
}
public class Route<T1, T2> : Route
{
private Func<RouteContext, T1, T2, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1])
);
}
}
public class Route<T1, T2, T3> : Route
{
private Func<RouteContext, T1, T2, T3, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, T3, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, T3, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1]),
RouteArgumentConverter.Convert<T3>(arguments[2])
);
}
}
public class Route<T1, T2, T3, T4> : Route
{
private Func<RouteContext, T1, T2, T3, T4, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, T3, T4, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, T3, T4, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1]),
RouteArgumentConverter.Convert<T3>(arguments[2]),
RouteArgumentConverter.Convert<T4>(arguments[3])
);
}
}
public class Route<T1, T2, T3, T4, T5> : Route
{
private Func<RouteContext, T1, T2, T3, T4, T5, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1]),
RouteArgumentConverter.Convert<T3>(arguments[2]),
RouteArgumentConverter.Convert<T4>(arguments[3]),
RouteArgumentConverter.Convert<T4>(arguments[4])
);
}
}
public class Route<T1, T2, T3, T4, T5, T6> : Route
{
private Func<RouteContext, T1, T2, T3, T4, T5, T6, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, T6, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, T6, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1]),
RouteArgumentConverter.Convert<T3>(arguments[2]),
RouteArgumentConverter.Convert<T4>(arguments[3]),
RouteArgumentConverter.Convert<T4>(arguments[4]),
RouteArgumentConverter.Convert<T4>(arguments[5])
);
}
}
public class Route<T1, T2, T3, T4, T5, T6, T7> : Route
{
private Func<RouteContext, T1, T2, T3, T4, T5, T6, T7, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, T6, T7, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, T6, T7, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1]),
RouteArgumentConverter.Convert<T3>(arguments[2]),
RouteArgumentConverter.Convert<T4>(arguments[3]),
RouteArgumentConverter.Convert<T4>(arguments[4]),
RouteArgumentConverter.Convert<T4>(arguments[5]),
RouteArgumentConverter.Convert<T4>(arguments[6])
);
}
}
public class Route<T1, T2, T3, T4, T5, T6, T7, T8> : Route
{
private Func<RouteContext, T1, T2, T3, T4, T5, T6, T7, T8, HttpListenerResponse> Target;
public Route(string method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, T6, T7, T8, HttpListenerResponse> target, bool closeResponse = true)
{
this.Method = method;
this.Syntax = syntax;
this.Target = target;
this.CloseResponse = closeResponse;
}
public Route(HttpRequestMethod method, string syntax, Func<RouteContext, T1, T2, T3, T4, T5, T6, T7, T8, HttpListenerResponse> target, bool closeResponse = true)
: this(method.ToString(), syntax, target, closeResponse) { }
public override void Invoke(RouteContext context, params string[] arguments)
{
this.Target.DynamicInvoke(
context,
RouteArgumentConverter.Convert<T1>(arguments[0]),
RouteArgumentConverter.Convert<T2>(arguments[1]),
RouteArgumentConverter.Convert<T3>(arguments[2]),
RouteArgumentConverter.Convert<T4>(arguments[3]),
RouteArgumentConverter.Convert<T4>(arguments[4]),
RouteArgumentConverter.Convert<T4>(arguments[5]),
RouteArgumentConverter.Convert<T4>(arguments[6]),
RouteArgumentConverter.Convert<T4>(arguments[7])
);
}
}
}

View File

@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// A class to help convert route arguments.
/// </summary>
internal class RouteArgumentConverter
{
/// <summary>
/// Converts a string to a given type if possible. Otherwise returns default of T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="input"></param>
/// <returns></returns>
public static T Convert<T>(string input)
{
var typeCode = Type.GetTypeCode(typeof(T));
if (typeCode == TypeCode.String)
{
return (dynamic)input;
}
else if (typeCode == TypeCode.Object)
{
var castOperator = typeof(T).GetMethod("op_Explicit", new[] { typeof(string) });
if (castOperator == null)
return default(T);
return (T)castOperator.Invoke(null, new[] { input });
}
else if (typeCode == TypeCode.Double)
{
double.TryParse(input, out double result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Single)
{
float.TryParse(input, out float result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Decimal)
{
decimal.TryParse(input, out decimal result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Int64)
{
long.TryParse(input, out long result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Int32)
{
int.TryParse(input, out int result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Int16)
{
short.TryParse(input, out short result);
return (dynamic)result;
}
else if (typeCode == TypeCode.SByte)
{
sbyte.TryParse(input, out sbyte result);
return (dynamic)result;
}
else if (typeCode == TypeCode.UInt64)
{
ulong.TryParse(input, out ulong result);
return (dynamic)result;
}
else if (typeCode == TypeCode.UInt32)
{
uint.TryParse(input, out uint result);
return (dynamic)result;
}
else if (typeCode == TypeCode.UInt16)
{
ushort.TryParse(input, out ushort result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Byte)
{
byte.TryParse(input, out byte result);
return (dynamic)result;
}
else if (typeCode == TypeCode.Boolean)
{
if (input == "f" || input == "0" || input == "F")
return (dynamic)false;
bool.TryParse(input, out bool result);
return ((dynamic)result);
}
else if (typeCode == TypeCode.DateTime)
{
DateTime.TryParse(input, out DateTime result);
return ((dynamic)result);
}
else if (typeCode == TypeCode.Char)
{
char.TryParse(input, out char result);
return ((dynamic)result);
}
return default(T);
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// An outline of a Route Context which includes
/// the request and response for a route.
/// </summary>
public class RouteContext
{
/// <summary>
/// The Http Request that requested this route.
/// </summary>
public HttpListenerRequest Request = null;
/// <summary>
/// The Http Response for this route.
/// </summary>
public HttpListenerResponse Response = null;
/// <summary>
/// Creates a new RouteContext with a given request and response.
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
public RouteContext(HttpListenerRequest request, HttpListenerResponse response)
{
this.Request = request;
this.Response = response;
}
}
}

View File

@@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// The outline of a Route listener that listens for http requests and invokes
/// matching routes.
/// </summary>
public class RouteListener
{
/// <summary>
/// The internal http listener.
/// </summary>
private HttpListener HttpListener = null;
/// <summary>
/// The list of routes this RouteListener is listening for.
/// </summary>
public List<Route> Routes = new List<Route>();
/// <summary>
/// The port this RouteListener is listening on.
/// </summary>
public ushort Port = 8081;
/// <summary>
/// Creates a new RouteListener with the default port number.
/// </summary>
public RouteListener()
{
}
/// <summary>
/// Creates a nwe RouteListener with a series of routes.
/// </summary>
/// <param name="routes">The routes to listen for.</param>
public RouteListener(params Route[] routes)
{
this.Routes = routes.ToList();
}
/// <summary>
/// Creates a new RouteListener with a port to listen on and a series of routes.
/// </summary>
/// <param name="port">The port number the listener should use.</param>
/// <param name="routes">The routes to listen for.</param>
public RouteListener(ushort port, params Route[] routes)
{
this.Routes = routes.ToList();
this.Port = port;
}
/// <summary>
/// Starts this RouteListener if it's not already running.
/// </summary>
public void Start()
{
if (this.HttpListener == null)
{
this.HttpListener = new HttpListener();
//Support listening on Windows & Linux.
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
this.HttpListener.Prefixes.Add($"http://localhost:{this.Port}/");
this.HttpListener.Prefixes.Add($"http://127.0.0.1:{this.Port}/");
}
else
{
this.HttpListener.Prefixes.Add($"http://*:{this.Port}/");
}
this.HttpListener.Start();
this.Listen();
}
}
/// <summary>
/// Function that does the actual listening.
/// </summary>
private void Listen()
{
ThreadPool.QueueUserWorkItem((o) =>
{
try
{
while (this.HttpListener.IsListening)
{
ThreadPool.QueueUserWorkItem((item) =>
{
var ctx = item as HttpListenerContext;
try
{
bool handled = false;
bool close = true;
string[] arguments = null;
for (int i = 0; i < this.Routes.Count; i++)
{
if (this.Routes[i].Method.ToUpper() == ctx.Request.HttpMethod.ToUpper() && RouteMatcher.Matches(ctx.Request.Url.AbsolutePath, this.Routes[i].Syntax, out arguments))
{
handled = true;
close = this.Routes[i].CloseResponse;
//Make sure if the route fails we don't die here, just set the response to internal server error.
try
{
this.Routes[i].Invoke(new RouteContext(ctx.Request, ctx.Response), arguments);
}
catch
{
ctx.Response.WithStatus(HttpStatusCode.InternalServerError);
}
break;
}
}
if (!handled)
ctx.Response.WithStatus(HttpStatusCode.BadRequest);
if (close)
ctx.Response.Close();
}
catch (Exception ex)
{
ctx.Response.WithStatus(HttpStatusCode.InternalServerError);
ctx.Response.Close();
}
}, this.HttpListener.GetContext());
}
}
catch { }
});
}
/// <summary>
/// Stops this RouteListener if it's running.
/// </summary>
public void Stop()
{
if (this.HttpListener != null)
{
try
{
this.HttpListener.Stop();
this.HttpListener = null;
}
catch
{
this.HttpListener = null;
}
}
}
/// <summary>
/// Blocks the current thread indenfinitly while this RouteListner is running.
/// </summary>
public void Block()
{
while (this.HttpListener != null)
if (!Thread.Yield())
Thread.Sleep(1000);
}
}
}

View File

@@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// A class to help match route syntaxs against requests.
/// </summary>
public class RouteMatcher
{
/// <summary>
/// Check to see if a url matches a given route syntax.
/// * = any path segment will match
/// ** = anything from this point forward is accepted
/// {} = route parameter
/// ! = must not match
/// || = logical or
/// && = logical and
///
/// Note:
/// If route parameter doesn't end with /, then the parameter will be the rest of the url.
/// Example:
/// </summary>
/// <param name="url"></param>
/// <param name="syntax"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static bool Matches(string url, string syntax, out string[] arguments)
{
//Set the arguments to null, initially.
arguments = null;
//Trim the url and the syntax.
url = url.Trim();
syntax = syntax.Trim();
//Split the url and the syntax into path segments
var urlSegments = url.Split('/').Where(segment => segment.Length > 0).Select(segment => segment.Trim()).ToArray();
var syntaxSegments = syntax.Split('/').Where(segment => segment.Length > 0).Select(segment => segment.Trim()).ToArray();
//If we have no syntax segments this is not a match.
if (syntaxSegments.Length == 0)
return false;
//If we have segments and the url does not then this may not be a match.
if (urlSegments.Length == 0 && syntaxSegments[0] == "**")
return true;
else if (urlSegments.Length == 0 && syntaxSegments.Length == 1 && syntaxSegments[0] == "*")
return true;
//Count the number of arguments in the syntax and set it.
arguments = new string[syntax.Count('{')];
int argumentIndex = 0;
//Check each segment against the url.
var max = Math.Min(urlSegments.Length, syntaxSegments.Length);
for (int i = 0; i < max; i++)
{
var syntaxSegment = syntaxSegments[i];
if (syntaxSegment == "**")
{
return true;
}
else if (syntaxSegment.StartsWith("{") && syntaxSegment.EndsWith("}") && i + 1 >= syntaxSegments.Length && syntax.EndsWith("/") == false)
{
//Special case, syntax ends with a parameter, so recombine the rest of the url and add it as a parameter.
var key = syntaxSegment.Substring(1, syntaxSegment.Length - 2);
var builder = new StringBuilder();
for (int i2 = i; i2 < urlSegments.Length; i2++)
builder.Append(urlSegments[i2]).Append(i2 + 1 < urlSegments.Length ? "/" : "");
arguments[argumentIndex++] = builder.ToString();
return true;
}
else if (SegmentMatches(urlSegments[i], syntaxSegment, arguments, ref argumentIndex) == false)
{
return false;
}
}
if (urlSegments.Length > syntaxSegments.Length)
return false;
else if (syntaxSegments.Length > urlSegments.Length)
return false;
else
return true;
}
private static bool SegmentMatches(string segment, string syntax, string[] arguments, ref int argumentIndex)
{
//Split the syntax into conditions
string[] conditions = syntax.Split(' ').Where(condition => condition.Length > 0).ToArray();
//Based off the matches, see if the segment matches.
bool match = false;
for (int i = 0; i < conditions.Length; i++)
{
var condition = conditions[i];
if (condition == "*")
{
match = true;
}
else if (condition == "**")
{
return true;
}
else if (condition.StartsWith("!"))
{
if (condition.Substring(1) == segment)
match = false;
else
match = true;
}
else if (condition.StartsWith("{") && condition.EndsWith("}"))
{
var key = condition.Substring(1, condition.Length - 2);
arguments[argumentIndex++] = segment;
match = true;
}
else if (condition == "&&")
{
if (match == false)
return false;
}
else if (condition == "||")
{
if (match)
return true;
}
else if (condition == segment)
{
return true;
}
}
return match;
}
}
}