【发布时间】:2019-07-14 21:54:52
【问题描述】:
我正在开发一个 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 代码来检查会话是否为空,但 HttpContext.Current.Session["userName"] 始终为空并在循环中进入登录页面。
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
{
【问题讨论】:
-
你如何验证用户。我的意思是表单身份验证?
-
我建议您将 web.config 中的 timeout 属性的值增加到 20 并检查。 1 太低了。
-
是的,我正在使用表单身份验证进行身份验证。我已将超时设置为 20,但会话仍然为空
标签: c# asp.net-mvc asp.net-mvc-5 attributes