minor fixes for api

This commit is contained in:
2024-08-17 10:12:44 +02:00
parent f509c53836
commit aed2cc4d88
2 changed files with 15 additions and 6 deletions

View File

@@ -27,6 +27,7 @@ public class ApiServer(string apiUrl) : IApiServer
public virtual void Start()
{
Log.Info("Start listening");
httpListener.Prefixes.Add(ApiUrl + "/");
httpListener.Start();
Listen();
}
@@ -44,21 +45,27 @@ public class ApiServer(string apiUrl) : IApiServer
// Register each method
foreach (var method in methods)
RegisterHandler(method.CreateDelegate(instance));
RegisterHandler(method.CreateDelegate(instance), false);
}
public virtual void RegisterHandler(Delegate handler)
{
RegisterHandler(handler, true);
}
public virtual void RegisterHandler(Delegate handler, bool throwOnError)
{
var method = handler.Method;
// Sanity checks
if (method.GetCustomAttribute<MessageHandlerAttribute>() is not MessageHandlerAttribute attribute
|| method.GetParameters().FirstOrDefault() is not ParameterInfo parameter
|| !parameter.ParameterType.IsGenericType
|| parameter.ParameterType.GenericTypeArguments.Length != 1
|| !parameter.ParameterType.GenericTypeArguments[0].IsAssignableTo(typeof(ApiMessage))
|| !method.ReturnType.IsAssignableTo(typeof(ApiResult)))
throw new NotSupportedException("The first parameter needs to be of type ApiMessage and must return an ApiResult object and the method must have the MessageHandlerAttribute.");
{
if (throwOnError)
throw new NotSupportedException("The first parameter needs to be of type ApiMessage and must return an ApiResult object and the method must have the MessageHandlerAttribute.");
return;
}
// Add handler
var fullUrl = attribute.Route;
@@ -137,7 +144,7 @@ public class ApiServer(string apiUrl) : IApiServer
Log.Info("Write response");
context.Response.ContentType = "application/json";
using StreamWriter output = new(context.Response.OutputStream);
output.Write(result);
output.Write(result.ResultJson);
}
Log.Debug("Finish response");

View File

@@ -23,4 +23,6 @@ public interface IApiServer
void RegisterHandler<T>(T instance) where T : class;
void RegisterHandler(Delegate handler);
void RegisterHandler(Delegate handler, bool throwOnError);
}