Files
BeWoPlaner/Service/ServiceBehavior/JsonError/JsonErrorHandler.cs
2025-06-10 14:29:34 +02:00

107 lines
2.7 KiB
C#

using BeWo.Data.Access;
using BeWo.Service.ServiceUtils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace BeWo.Service.ServiceBehavior.JsonError
{
[DataContract]
public class JsonError
{
[DataMember]
public string Message { get; set; }
[DataMember]
public string StackTrace { get; set; }
[DataMember]
public string ExceptionType { get; set; }
}
public class JsonErrorHandler : IErrorHandler
{
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
ServiceHelper.CoreLogger.LogError(error, nameof(JsonErrorHandler));
// Erstelle eine JSON-Fehlermeldung
var jsonError = new JsonError
{
Message = error.Message,
ExceptionType = error.GetType().Name
};
// Fügt StackTrace hinzu (AppSettings)
string val = ConfigurationManager.AppSettings["AdminServiceEnableStackTrace"];
if(bool.TryParse(val, out bool res) && res)
{
jsonError.StackTrace = error.StackTrace;
}
// Serialisiere das JSON-Objekt
var serializer = new DataContractJsonSerializer(typeof(JsonError));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, jsonError);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
string jsonString = reader.ReadToEnd();
fault = Message.CreateMessage(version, null, new JsonBodyWriter(jsonString));
}
}
// Setze den Content-Type auf application/json
var webBodyFormat = WebBodyFormatMessageProperty.Name;
if (!fault.Properties.ContainsKey(webBodyFormat))
{
fault.Properties.Add(webBodyFormat, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
}
var httpResponse = new HttpResponseMessageProperty
{
StatusCode = System.Net.HttpStatusCode.InternalServerError,
StatusDescription = "Internal Server Error",
};
httpResponse.Headers["Content-Type"] = "application/json";
fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
}
public bool HandleError(Exception error)
{
// Gib an, ob der Fehler behandelt wurde
return true;
}
}
public class JsonBodyWriter : BodyWriter
{
private readonly string _json;
public JsonBodyWriter(string json) : base(true)
{
_json = json;
}
protected override void OnWriteBodyContents(System.Xml.XmlDictionaryWriter writer)
{
writer.WriteStartElement("Binary");
byte[] jsonBytes = Encoding.UTF8.GetBytes(_json);
writer.WriteBase64(jsonBytes, 0, jsonBytes.Length);
writer.WriteEndElement();
}
}
}