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() public virtual void Start()
{ {
Log.Info("Start listening"); Log.Info("Start listening");
httpListener.Prefixes.Add(ApiUrl + "/");
httpListener.Start(); httpListener.Start();
Listen(); Listen();
} }
@@ -44,21 +45,27 @@ public class ApiServer(string apiUrl) : IApiServer
// Register each method // Register each method
foreach (var method in methods) foreach (var method in methods)
RegisterHandler(method.CreateDelegate(instance)); RegisterHandler(method.CreateDelegate(instance), false);
} }
public virtual void RegisterHandler(Delegate handler) public virtual void RegisterHandler(Delegate handler)
{
RegisterHandler(handler, true);
}
public virtual void RegisterHandler(Delegate handler, bool throwOnError)
{ {
var method = handler.Method; var method = handler.Method;
// Sanity checks // Sanity checks
if (method.GetCustomAttribute<MessageHandlerAttribute>() is not MessageHandlerAttribute attribute if (method.GetCustomAttribute<MessageHandlerAttribute>() is not MessageHandlerAttribute attribute
|| method.GetParameters().FirstOrDefault() is not ParameterInfo parameter || 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))) || !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 // Add handler
var fullUrl = attribute.Route; var fullUrl = attribute.Route;
@@ -137,7 +144,7 @@ public class ApiServer(string apiUrl) : IApiServer
Log.Info("Write response"); Log.Info("Write response");
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
using StreamWriter output = new(context.Response.OutputStream); using StreamWriter output = new(context.Response.OutputStream);
output.Write(result); output.Write(result.ResultJson);
} }
Log.Debug("Finish response"); Log.Debug("Finish response");

View File

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