c# - 检查 ASP.NET Core 1.0 中的 session

标签 c# session asp.net-core

访问上下文的 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/

相关文章:

c# - Windows App Store - System.Net 命名空间 - 等效对象

.net - 解决错误 "Microsoft.NETCore.App 1.0.0 does not support framework .NETFramework,Version=v4.6.1"

c# - 要让我的网站在移动浏览器上运行,我需要知道什么?

c# - 服务器架构

php - 在具有不同域的多个服务器之间共享 SESSION

java - spring在redis中存储session的方法

azure - 从asp.net core 2.2 Web应用程序读取Azure容器实例 secret 卷

c# - ASP.Net Core WebAPI - 请求的资源上不存在 'Access-Control-Allow-Origin' header

c# - ListView中的"Value does not fall within the expected range"异常

php - 文件上传返回上传html页面