Die Das Unit-Test-Projekt für das Dienstprojekt zielt auch auf .NET 4.7.1 und .NET 8.0 ab.
Alle Unit-Tests bestehen mit .NET 4.7.1.
Das Dienstprojekt verwendet ein SessionBag-Objekt, das über einen bedingten Compiler für .NET 4.7.1 und .NET 8.0 verfügt.
Die Sitzung in . NET 4.7.1 kann Elemente ohne Serialisierung und Deserialisierung auf einen bestimmten Typ speichern. Die Komponententests funktionieren also.
Die Sitzung in .NET 8.0 benötigt Elemente als Byte[] zum Speichern und Deserialisieren beim Abrufen aus Byte[] auf den spezifischen benötigten Klassentyp.
Dies ist die SessionBag-Klasse:
Code: Select all
public class SessionBag : DynamicObject
{
private static SessionBag current;
private static object session;
static SessionBag()
{
current = new SessionBag();
}
// Session Property
// Indexer
// Other code
// Setting data to Session
#if NET8_0_OR_GREATER
if (value != null)
{
// Serialize object to byte[] and store in session
Session.Set(key, SerializeObject(value));
}
else
{
Session.Remove(key);
}
#else
Session.Add(key, value);
#endif
// Retrieving Data from Session
// DynamicObject overrides to make SessionBag dynamic
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (Session != null)
{
#if NET8_0_OR_GREATER
if (Session.TryGetValue(binder.Name, out byte[] val))
{
result = Deserialize(val); // Use Deserialize directly to determine the type
}
else
{
result = null;
}
#else
result = Session[binder.Name];
#endif
}
else
{
result = null;
}
return true;
}
// Deserialize based on type checks (string, string[], UserInfo, UserRoles)
private static object Deserialize(byte[] byteArray)
{
if (byteArray == null)
return null;
string jsonString = Encoding.UTF8.GetString(byteArray);
// Deserialize with custom options to handle enum as string
var options = new JsonSerializerOptions
{
Converters = { new JsonStringEnumConverter() } // Enable string enum conversion
};
return JsonSerializer.Deserialize(jsonString);
//return JsonSerializer.Deserialize(jsonString);
}
}
Der Service-Layer-Code gibt bei der Konvertierung Null zurück .
Code: Select all
SessionBag.Current.UserData As UserData
Code: Select all
SessionBag.Current.UserData
Ich habe festgestellt, dass die UserData-Klasse eine Enum-Eigenschaft hat und wie hier gezeigt dekoriert ist, aber sie schlägt immer noch fehl.Bitte um Rat.
Code: Select all
public class User
{
public decimal Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public UserType Type { get; set; }
}
public enum UserType
{
Type1 = 0,
Type2 = 1,
Type3 = 2,
}