From 24cde0bd032ce28c62492df2e60ae3dd8945a1a0 Mon Sep 17 00:00:00 2001 From: Pilzinsel64 Date: Tue, 18 Mar 2025 08:56:08 +0100 Subject: [PATCH] better support of raw data transfer --- Pilz.Net/Api/ApiClient.cs | 11 ++++++++++- Pilz.Net/Api/ApiRawMessage.cs | 6 ++++++ Pilz.Net/Api/ApiServer.cs | 5 +++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 Pilz.Net/Api/ApiRawMessage.cs diff --git a/Pilz.Net/Api/ApiClient.cs b/Pilz.Net/Api/ApiClient.cs index 9ee481e..1ee1255 100644 --- a/Pilz.Net/Api/ApiClient.cs +++ b/Pilz.Net/Api/ApiClient.cs @@ -55,7 +55,16 @@ public class ApiClient(string apiUrl) : IApiClient TResponse? result = null; if (res.IsSuccessStatusCode) - result = serializer.Deserialize(await res.Content.ReadAsStringAsync(), typeof(TResponse)) as TResponse; + { + var mediaType = res.Content.Headers.ContentType?.MediaType; + if (!string.IsNullOrWhiteSpace(mediaType)) + { + if (mediaType == "application/json") + result = serializer.Deserialize(await res.Content.ReadAsStringAsync(), typeof(TResponse)) as TResponse; + else if (typeof(TResponse).IsAssignableTo(typeof(ApiRawMessage)) && mediaType == "application/octet-stream") + result = (TResponse)(object)new ApiRawMessage(await res.Content.ReadAsByteArrayAsync()); + } + } return new(res, result); } diff --git a/Pilz.Net/Api/ApiRawMessage.cs b/Pilz.Net/Api/ApiRawMessage.cs new file mode 100644 index 0000000..90f3325 --- /dev/null +++ b/Pilz.Net/Api/ApiRawMessage.cs @@ -0,0 +1,6 @@ +namespace Pilz.Net.Api; + +public class ApiRawMessage(byte[] data) : ApiMessage +{ + public byte[] Data { get; } = data; +} diff --git a/Pilz.Net/Api/ApiServer.cs b/Pilz.Net/Api/ApiServer.cs index fe05fde..6a6e10b 100644 --- a/Pilz.Net/Api/ApiServer.cs +++ b/Pilz.Net/Api/ApiServer.cs @@ -411,6 +411,7 @@ public class ApiServer : IApiServer else if (result.ResultContent is byte[] resultBytes) { Log.Info("Sending raw bytes response for " + context.Request.RawUrl); + context.Response.ContentType = "application/octet-stream"; context.Response.OutputStream.Write(resultBytes, 0, resultBytes.Length); context.Response.OutputStream.Flush(); } @@ -455,6 +456,10 @@ public class ApiServer : IApiServer if (result.Message is null) return new(result, null); + // Return result with raw data + if (result.Message is ApiRawMessage dataMsg) + return new(result, dataMsg.Data); + // Serializer Log.Debug("Serialize message"); if (serializer.Serialize(result.Message) is not string resultStr)