访问上下文的 Session 属性会引发异常,因为未配置 session 。
如何检测 session 是否可用(如果 session 可以根据配置打开或关闭)。
换句话说,我不能这样做:context.Session?.Clear();
最佳答案
我认为最安全、最高效的方法是使用 request features 。例如,这是一个简单的扩展方法,用于获取 session 或 null(如果未启用):
public static ISession SafeSession(this HttpContext httpContext)
{
var sessionFeature = httpContext.Features.Get<ISessionFeature>();
return sessionFeature == null ? null : httpContext.Session;
}
MVC Controller 的使用示例:
var session = this.HttpContext.SafeSession();
关于c# - 检查 ASP.NET Core 1.0 中的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42345078/