Session of Asp.NetCore
- MVC 和 Asp.NetCore开发得差别在哪里?
-
- ISession 声明最小化
- 自带有的扩展方法
- Session 的扩展.
MVC 和 Asp.NetCore开发得差别在哪里?
声明最小化,然后扩展方法增强API。以Session为例:
ISession 声明最小化
namespace Microsoft.AspNetCore.Http
{
public interface ISession
{
//
// Summary:
// A unique identifier for the current session. This is not the same as the session
// cookie since the cookie lifetime may not be the same as the session entry lifetime
// in the data store.
string Id { get; }
//
// Summary:
// Indicate whether the current session has loaded.
bool IsAvailable { get; }
//
// Summary:
// Enumerates all the keys, if any.
IEnumerable<string> Keys { get; }
//
// Summary:
// Remove all entries from the current session, if any. The session cookie is not
// removed.
void Clear();
//
// Summary:
// Store the session in the data store. This may throw if the data store is unavailable.
Task CommitAsync(CancellationToken cancellationToken = default);
//
// Summary:
// Load the session from the data store. This may throw if the data store is unavailable.
Task LoadAsync(CancellationToken cancellationToken = default);
//
// Summary:
// Remove the given key from the session if present.
//
// Parameters:
// key:
void Remove(string key);
//
// Summary:
// Set the given key and value in the current session. This will throw if the session
// was not established prior to sending the response.
//
// Parameters:
// key:
//
// value:
void Set(string key, byte[] value);
//
// Summary:
// Retrieve the value of the given key, if present.
//
// Parameters:
// key:
//
// value:
bool TryGetValue(string key, out byte[] value);
}
自带有的扩展方法
namespace Microsoft.AspNetCore.Http
{
public static class SessionExtensions
{
public static byte[] Get(this ISession session, string key);
public static int? GetInt32(this ISession session, string key);
public static string GetString(this ISession session, string key);
public static void SetInt32(this ISession session, string key, int value);
public static void SetString(this ISession session, string key, string value);
}
}
Session 的扩展.
- 背景:我们发现系统默认提供的Session方法,仅能存储byte、string、int类型,很不灵活,我们想能存储任何对象,这个时候就需要我们自行扩展。
-
利用Newtonsoft.Json进行扩展
All session data must be serialized to enable a distributed cache scenario, even when using the in-memory cache. String and integer serializers are provided by the extension methods of ISession. Complex types must be serialized by the user using another mechanism, such as JSON.
扩展代码详见SessionExtensions中的Set和Get方法:
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}