发布后会话丢失(适用于开发机器)

时间:2013-03-07 15:06:35

标签: c# asp.net session telerik

我正在使用Holiday Tracker应用程序而且一个特定的事情正在扼杀整个"页面生命周期"。

在我的用户计划程序中,每个用户都可以插入他的假期,有时它可以正常工作(因此他可以插入/删除/编辑并查看他的假期)。还有一个度假页面(那里有相同的故事,只有一个网格)。

但有时设置的会话会丢失。如果我正在使用Visual Studio 2012进行调试,那么它正在运行。但是,如果我发布该应用程序,它就无法运行。它会以某种方式迷失

Global.asax.cs中的代码

    void Session_Start(object sender, EventArgs e) {
        // Code that runs when a new session is started
        if (HttpContext.Current.User != null && HttpContext.Current.User is HtUser)
        {
            HtUser user = (HtUser)HttpContext.Current.User;
            Session["UserId"] = user.UserId;
            if(user.HtDepartments.Any() && user.HtDepartments.First().HtBusinessUnit != null){
                int BusinessUnitId  = user.HtDepartments.First().HtBusinessUnit.BusinessUnitId;
                Session["BusinessUnitId"] = BusinessUnitId;
            }

        }
    }

我认为可能存在错误。

调度程序:

<%--<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">--%>

        <div style="float: left; margin-right: 20px; margin-bottom: 10px;">
            <asp:Label runat="server" Text="Unbooked vacation:"></asp:Label>
            <asp:Label ID="lblBookedVacation" runat="server" Text=""></asp:Label>
        </div>

        <div style="float: right; margin-right: 20px; margin-bottom: 10px;">
            <asp:Button runat="server" ID="btnExport" Text="Export to Lotus Notes" OnClientClick="Export(this, event); return false;" OnClick="btnExport_Click"></asp:Button>
        </div>
        <div style="clear: both;" />
        <div>
            <telerik:RadScheduler runat="server" ID="RadScheduler1" Width="750px" Height="700px"
                DayStartTime="07:00:00" DayEndTime="18:00:00" SelectedView="WeekView" DataSourceID="dsVactationDays"
                DataKeyField="VacationDayId" DataSubjectField="Title" DataStartField="FromDate" DataEndField="ToDate" OnAppointmentUpdate="RadScheduler1_AppointmentUpdate"
                OnAppointmentInsert="RadScheduler1_AppointmentInsert"
                OnRecurrenceExceptionCreated="RadScheduler1_RecurrenceExceptionCreated" OnTimeSlotCreated="RadScheduler1_TimeSlotCreated" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound">
                <AdvancedForm Modal="true"></AdvancedForm>
                <TimelineView UserSelectable="false"></TimelineView>
                <TimeSlotContextMenuSettings EnableDefault="true"></TimeSlotContextMenuSettings>
                <AppointmentContextMenuSettings EnableDefault="true"></AppointmentContextMenuSettings>
            </telerik:RadScheduler>
        </div>
        <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
        <asp:DataGrid runat="server" DataSourceID="dsVactationDays" AutoGenerateColumns="true"></asp:DataGrid>

        <asp:EntityDataSource ID="dsVactationDays" runat="server" ConnectionString="name=HolidayTrackerEntities" DefaultContainerName="HolidayTrackerEntities"
            EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="HtVacationDays"
            Where="it.UserId == @UserId">
            <WhereParameters>
                <asp:SessionParameter DbType="Int32" Name="UserId" SessionField="UserId" />
            </WhereParameters>
        </asp:EntityDataSource>

    <%--</telerik:RadAjaxPanel>--%>

背后的代码

   private const int AppointmentsLimit = 1;
       // private HtUser paramUser;
        private HtUser user;
        private HtUser User
        {
            get
            {
                if (user == null)
                {
                    user = HtUser.INIT_USER(this.Page, false);
                }
                return user;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                if (this.User != null) {
                    updateUnbookedVacationNotification();
                }
            }
            txtID.Text = Session["UserId"] != null ? Session["UserId"].ToString() : "FUUUUU";
        }

        private void updateUnbookedVacationNotification() {
            double avAmount = User.GetAnnualVacationAmountByYear(this.RadScheduler1.SelectedDate.Year);
            double bookedAmount = User.GetBookedVacation(this.RadScheduler1.SelectedDate.Year);
            this.lblBookedVacation.Text = (avAmount - bookedAmount).ToString();
        }

        //private void getParameters()
        //{
        //    if (Page.Request["UserId"] != null)
        //    {
        //        int userId = Constants.TryConvert(Page.Request["userId"], this.Page);
        //        this.paramUser = HtUser.GetById(userId);
        //    }

        //}
        private bool ExceedsLimit(Appointment apt)
        {
            int appointmentsCount = 0;
            foreach (Appointment existingApt in RadScheduler1.Appointments.GetAppointmentsInRange(apt.Start, apt.End))
            {
                if (existingApt.Visible)
                    appointmentsCount++;
            }

            return (appointmentsCount > AppointmentsLimit - 1);
        }

        private bool AppointmentsOverlap(Appointment appointment)
        {
            if (ExceedsLimit(appointment))
            {
                foreach (Appointment a in RadScheduler1.Appointments.GetAppointmentsInRange(appointment.Start, appointment.End))
                {
                    if (a.ID != appointment.ID)
                    {
                        return true;
                    }
                }
            }



            return false;
        }

        private void RegisterScript()
        {
            Label1.Text = "Invalid move! There are appointments arranged for this time period.";
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "LabelUpdated",
                    "$telerik.$('.lblError').show().animate({ opacity: 0.9 }, 2000).fadeOut('slow');", true);
        }


        protected void RadScheduler1_AppointmentInsert(object sender, SchedulerCancelEventArgs e)
        {
            if (ExceedsLimit(e.Appointment))
            {
                e.Cancel = true;
                RegisterScript();
            }
            else
            {
                int id = HtUser.GetUserIdByLogin(Page.User.Identity.Name);
                e.Appointment.Attributes.Add("UserId", id.ToString());
            }

        }

登录部分  的global.asax.cs

protected void WindowsAuthentication_OnAuthenticate(Object source, WindowsAuthenticationEventArgs e)
        {
            if (Request.Cookies.Get(Constants.AUTHORIZATION_COOKIE_NAME) != null)
                return;

            String strUserIdentity;
            FormsAuthenticationTicket formsAuthTicket;
            HttpCookie httpCook;
            String strEncryptedTicket;
            AdLookup adLookup = new AdLookup();

            strUserIdentity = e.Identity.Name;

            bool loggedIn = false;
            String email = null;
            String role = null;

            email = strUserIdentity; 
            HtUser userInfo = null;
            if (email != null && email != "")
            {
                userInfo = HtUser.GetByLogin(e.Identity, email);

                if (userInfo != null && userInfo.UserName.Length > 0)
                {
                    loggedIn = true;
                    role = HtUser.GetUserRoleString(userInfo);
                }
                //Checks if user is in domain
                else
                {
                    userInfo = adLookup.GetAdUserByUsername(HtUser.getUserNameFromDomainString(email));
                    if (userInfo != null && userInfo.UserName.Length > 0)
                    {
                        loggedIn = true;
                        role = UserRoles.User;
                    }
                }
            }
            //}

            if (loggedIn)
            {
                formsAuthTicket = new FormsAuthenticationTicket(1, email, DateTime.Now,
                                                                DateTime.Now.AddMinutes(60), false, role);
                strEncryptedTicket = FormsAuthentication.Encrypt(formsAuthTicket);
                httpCook = new HttpCookie(Constants.AUTHORIZATION_COOKIE_NAME, strEncryptedTicket);
                Response.Cookies.Add(httpCook);
                HttpContext.Current.User = userInfo;
            }
            else
            {
                HttpContext.Current.User = null;
            }

的Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
    <add name="ConnectionString" connectionString="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;Persist Security Info=True;User ID=sa;Password=123.;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
    <add name="HolidayTrackerConnectionString" connectionString="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;User ID=sa;Password=123." providerName="System.Data.SqlClient" />
    <add name="HolidayTrackerEntities" connectionString="metadata=res://*/Model.HolidayTracker.csdl|res://*/Model.HolidayTracker.ssdl|res://*/Model.HolidayTracker.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;Persist Security Info=True;User ID=sa;Password=123.;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
    <add name="HolidayTrackerEntities1" connectionString="metadata=res://*/DAL.HTTracker.csdl|res://*/DAL.HTTracker.ssdl|res://*/DAL.HTTracker.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ch-s-0008086;initial catalog=HolidayTracker;user id=sa;password=123.;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="LDAP_SERVER_NAME" value="asdasdasd" />
    <add key="LDAP_USERNAME" value="asdasdas" />
    <add key="LDAP_PASSWORD" value="asdasdasd" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Speech, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <customErrors mode="Off" />
    <authentication mode="Windows" />
    <identity impersonate="false" />
    <httpHandlers>
      <add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false" />
      <add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false" />
      <add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false" />
      <add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
      <add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
      </controls>
    </pages>
    <httpModules>
      <add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" />
      <add name="RadCompression" type="Telerik.Web.UI.RadCompression" /></httpModules>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="RadUploadModule" />

      <remove name="RadCompression" /><add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode" />
      <add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode" /></modules>
    <handlers>
      <remove name="ChartImage_axd" />
      <remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
      <remove name="Telerik_Web_UI_DialogHandler_aspx" />
      <remove name="Telerik_RadUploadProgressHandler_ashx" />
      <remove name="Telerik_Web_UI_WebResource_axd" />
      <add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode" />
      <add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode" />
      <add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode" />
      <add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode" />
      <add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode" />
    </handlers>
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

如果您需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

如果您正在使用InProc会话存储并发布应用程序,则IIS会回收应用程序池,并重新生成w3wp.exe进程。您的会话数据会立即丢失。

如果这是您遇到的问题,并且您想要避免它,则可以选择将会话存储在其他位置(例如在数据库中)。有关详细信息,请参阅ASP.NET Session-State Modes上的MSDN文章。