C# 会话到期属性不存在';不要被服务器解雇

C# 会话到期属性不存在';不要被服务器解雇,c#,asp.net-mvc-4,session-variables,actionfilterattribute,C#,Asp.net Mvc 4,Session Variables,Actionfilterattribute,我正在尝试跟踪会话过期情况,当应用程序在我的开发PC上运行时,一切都正常。但它在live server上的工作情况与预期不同。我已经重新启动服务器,但没有运气!我在windows server 2012(windows azure vm)和IIS 8上运行 我收到了一个类似的错误,基于其操作被触发的控制器。由于会话变量_connectionstring在会话过期时为null,控制器初始化失败,因此生成错误 如果我将sessionState改为1,将timeout改为2,那么重定向在服务器和开发环

我正在尝试跟踪会话过期情况,当应用程序在我的开发PC上运行时,一切都正常。但它在live server上的工作情况与预期不同。我已经重新启动服务器,但没有运气!我在windows server 2012(windows azure vm)和IIS 8上运行

我收到了一个类似的错误,基于其操作被触发的控制器。由于会话变量_connectionstring在会话过期时为null,控制器初始化失败,因此生成错误

如果我将sessionState改为1,将timeout改为2,那么重定向在服务器和开发环境中都能正常工作。奇怪

我的问题是,为什么操作筛选器在live server环境中不起作用?它在开发环境下工作得非常好。我错过了什么

下面是我的代码

Web.Config:

<system.web>
    <sessionState mode="InProc" timeout="20" />
    <authentication mode="Forms">
        <forms loginUrl="~/Auth/Login" timeout="25" slidingExpiration="true" />
    </authentication>
</system.web>
过滤器:

public class SessionExpireFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(SkipActionFilterAttribute), false).Any())
        {
            return;
        }

        HttpContextBase ctx = filterContext.HttpContext;
        //HttpContext ctx = HttpContext.Current;

        // check if session is supported
        if (ctx.Session != null)
        {
            // check if a new session id was generated
            if (ctx.Session.IsNewSession)
            {
                // If it says it is a new session, but an existing cookie exists, then it must
                // have timed out
                string sessionCookie = ctx.Request.Headers["Cookie"];
                if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        // For AJAX requests, we're overriding the returned JSON result with a simple string,
                        // indicating to the calling JavaScript code that a redirect should be performed.
                        filterContext.Result = new JsonResult { Data = "_Logon_" };
                    }
                    else
                    {
                        filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary {
                            { "action", "SessionTimeout" },
                            { "controller", "Session" }});
                    }
                }
            }
        }

        base.OnActionExecuting(filterContext);
    }
}

//[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class LocsAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(SkipActionFilterAttribute), false).Any())
        {
            return;
        }
        HttpContext ctx = HttpContext.Current;

        // If the browser session has expired...
        if (ctx.Session["UserName"] == null)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                // For AJAX requests, we're overriding the returned JSON result with a simple string,
                // indicating to the calling JavaScript code that a redirect should be performed.
                filterContext.Result = new JsonResult { Data = "_Logon_" };
            }
            else
            {
                // For round-trip posts, we're forcing a redirect to Home/TimeoutRedirect/, which
                // simply displays a temporary 5 second notification that they have timed out, and
                // will, in turn, redirect to the logon page.
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {
                            { "action", "SessionTimeout" },
                            { "controller", "Session" }});
            }
        }
        else if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            // Otherwise the reason we got here was because the user didn't have access rights to the
            // operation, and a 403 should be returned.
            filterContext.Result = new HttpStatusCodeResult(403);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

public class SkipActionFilterAttribute : Attribute
{
}

最后我找到了行为不端的原因

当IIS>应用程序池>高级设置>空闲超时(分钟)设置在会话状态之前达到超时时,我的操作筛选器不会启动。默认值为20

将该值设置为0将禁用IIS idel超时。

它将给出错误信息

错误:会话超时参数的值无效。输入一个小于或等于500000的正整数

你可以试试

if ((Session["project"] == null) && (Session["User"] == null) && (Label1.Text == "Label") && (Label2.Text == "Label"))

    {
        Session.Abandon();
        Response.Redirect("Default.aspx");
    }

    else
    {

        if ((Session["User"] == null) || (Session["project"] == null))

        {
            Session["project"] = Label1.Text;
            Session["User"] = Label2.Text;
        }

        if ((Label1.Text == "Label") || (Label2.Text == "Label"))

        {
            Label1.Text = Session["project"].ToString();
            Label2.Text = Session["User"].ToString();
        }

    }

“使您的身份验证模式为无”而不是“IIS>Asp.net设置>身份验证模式”中的“窗口”

我猜您在本地使用visual studio开发服务器,在服务器上使用IIS。我想,这种会话使用模式取决于事件的管道顺序,而当IIS这样做时,会话还不存在,因为IIS默认处于集成模式。尝试更改为经典,或者更改会话的使用方式,使其与Integrated一起工作。此外,我认为有人否决了您的意见,因为这一问题的代码有点太多。是的,我在VS 2013 dev服务器上本地运行。你说的“会话还不存在”是什么意思?应用程序在会话到期之前一直平稳运行。当我设置非常短的会话超时(如1或2)时,它也会在服务器上正常运行。但如果我离开网页超过30分钟,action属性将不再触发。除此之外,只需加载连接字符串,根本不通过会话发送。您正在将其填充为一个静态变量,该变量将加载一次并在appdomain的生命周期内存在。我理解这对会话的其他用途没有帮助,但对于连接字符串来说,它没有意义。会话用于不稳定的用户数据,您需要不时地删除这些数据。类似于static constring=configugrationmanager.connectionString[“foo”]。connectionString感谢您的评论,但是可以根据用户或会话更改连接字符串。i、 e.我在应用程序中使用多个数据库。i、 e.所有用户都可以在登录时选择数据库。仅供参考:我曾尝试在经典模式下运行该应用程序,但得到了相同的行为。i、 e.筛选器不工作,并以NullReferenceException结束。
if ((Session["project"] == null) && (Session["User"] == null) && (Label1.Text == "Label") && (Label2.Text == "Label"))

    {
        Session.Abandon();
        Response.Redirect("Default.aspx");
    }

    else
    {

        if ((Session["User"] == null) || (Session["project"] == null))

        {
            Session["project"] = Label1.Text;
            Session["User"] = Label2.Text;
        }

        if ((Label1.Text == "Label") || (Label2.Text == "Label"))

        {
            Label1.Text = Session["project"].ToString();
            Label2.Text = Session["User"].ToString();
        }

    }