Refactoring
This commit is contained in:
56
AMWD.Common.AspNetCore/Extensions/SessionExtensions.cs
Normal file
56
AMWD.Common.AspNetCore/Extensions/SessionExtensions.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Microsoft.AspNetCore.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Extensions for the <see cref="ISession"/> object.
|
||||
/// </summary>
|
||||
public static class SessionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets a strong typed value.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The value type.</typeparam>
|
||||
/// <param name="session">The current session.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
public static void SetValue<T>(this ISession session, string key, T value)
|
||||
=> session.SetString(key, JsonConvert.SerializeObject(value));
|
||||
|
||||
/// <summary>
|
||||
/// Gets a strong typed value.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The value type.</typeparam>
|
||||
/// <param name="session">The current session.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>The value.</returns>
|
||||
public static T GetValue<T>(this ISession session, string key)
|
||||
=> session.HasKey(key) ? JsonConvert.DeserializeObject<T>(session.GetString(key)) : default;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a strong typed value or the fallback value.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The value type.</typeparam>
|
||||
/// <param name="session">The current session.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="fallback">A fallback value when the key is not present.</param>
|
||||
/// <returns>The value.</returns>
|
||||
public static T GetValue<T>(this ISession session, string key, T fallback)
|
||||
{
|
||||
if (session.HasKey(key))
|
||||
return session.GetValue<T>(key);
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the session has the key available.
|
||||
/// </summary>
|
||||
/// <param name="session">The current session.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><c>true</c> when the key was found, otherwise <c>false</c>.</returns>
|
||||
public static bool HasKey(this ISession session, string key)
|
||||
=> session.Keys.Contains(key);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user