在SessionTimeOut属性中,会话变量始终为null

时间:2019-02-21 04:43:35

标签: c# asp.net-mvc asp.net-mvc-5 attributes

我正在开发MVC 5应用程序。 以下是我在web.config中用于会话的代码。

<sessionState mode="InProc" cookieless="AutoDetect" timeout="1" />   

<pages enableSessionState="true">
    <namespaces>
        <add namespace="System.Web.Helpers"/>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Mvc.Routing"/>
        <add namespace="System.Web.WebPages"/>
    </namespaces>
</pages>

用户登录到应用程序时,我将其用户名存储在会话中。

我为SessionTimeOutAttribute使用以下代码来检查session是否为null,但是HttpContext.Current.Session["userName"]始终为null,并最终在登录页面中循环。

public class SessionTimeOutAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            if (HttpContext.Current.Session["userName"] ==null)
            {
                filterContext.Result = new RedirectResult("~/Session/Create");
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }

更新: 我在登录操作方法上使用了[AllowAnonymous]属性。

[AllowAnonymous]
[HttpPost]
public ActionResult Create(UserModel user)
{
    if (ModelState.IsValid){....}

如果登录成功,我将在会话Session["userName"] = userAccount.Username;中保存用户名

这是我在控制器上使用属性的方式

[Authorize]
[SessionTimeOut]
public class TestController : Controller
{

2 个答案:

答案 0 :(得分:0)

不查看所有代码,请执行以下操作:

  • 不要将此属性放在您的登录控制器或操作上。
  • 在登录操作/例程中,如果成功,则将用户名值设置为session。

如果将此属性注册为全局属性或将其置于具有登录操作的控制器的类级别,则将应用此属性并给您带来无限循环。

我建议不要将与会话交互的属性用作全局变量,因为某些控制器可能不需要会话状态。

答案 1 :(得分:0)

尝试将其更改为下面的web.config

<sessionState mode="InProc" cookieless="AutoDetect" timeout="20" /> 

其中超时是会话的到期时间。

相关问题