From aed2cc4d88d33d5fd8e8d29d8d6843fb4aab2a9f Mon Sep 17 00:00:00 2001 From: Pilzinsel64 Date: Sat, 17 Aug 2024 10:12:44 +0200 Subject: [PATCH] minor fixes for api --- Pilz.Net/Api/ApiServer.cs | 19 +++++++++++++------ Pilz.Net/Api/IApiServer.cs | 2 ++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Pilz.Net/Api/ApiServer.cs b/Pilz.Net/Api/ApiServer.cs index 3c720f4..e5b12a9 100644 --- a/Pilz.Net/Api/ApiServer.cs +++ b/Pilz.Net/Api/ApiServer.cs @@ -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() 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"); diff --git a/Pilz.Net/Api/IApiServer.cs b/Pilz.Net/Api/IApiServer.cs index 23107d5..3afc099 100644 --- a/Pilz.Net/Api/IApiServer.cs +++ b/Pilz.Net/Api/IApiServer.cs @@ -23,4 +23,6 @@ public interface IApiServer void RegisterHandler(T instance) where T : class; void RegisterHandler(Delegate handler); + + void RegisterHandler(Delegate handler, bool throwOnError); }