1

Update 1: If i set the session via ajax request, this session is not available to me when the js does does a refresh of the current action. Now, if i setup a session via non ajax requests then these are available inside other controller even ajax actions as well.

Update 2: By removing and adding the session helped with this issue

<modules runAllManagedModulesForAllRequests="true">
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
    </modules>

I am setting up a new site, this uses forms authentication that i am validating against the active directory. On successful authentication, i put the user class in the session and it is available to me when i check it right away.

//login user and put the user in session
AuthenticationHelper.LoginUser(user, loginModel.IsRememberMe);
//just checking
var userFromSession = AuthenticationHelper.GetUserFromSession();

public static void LoginUser(User user, bool isRememberMe)
        {
            //login user and put user in the session

            //log off first
            LogOff();

            //add user to session
            AddUserToSession(user);

            //sign in
            if (!isRememberMe)
            {
                //Set cookie
                FormsAuthentication.SetAuthCookie(user.UserId, false);
                /*
                GenericIdentity identity = new GenericIdentity(user.UserId);
                string[] roles = { person.PersonaType };
                GenericPrincipal principal = new GenericPrincipal(identity, roles);
                HttpContext.Current.User = principal;
                 */
            }
            else
            {
                //Create Persistent cookie
                var ticket = new FormsAuthenticationTicket(user.UserId, isRememberMe, 1);
                var encrypted = FormsAuthentication.Encrypt(ticket);
                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                authCookie.Expires = System.DateTime.Now.AddYears(1);
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Response.Cookies.Add(authCookie);
                }
            }
        }


public static void AddUserToSession(User user)
            {
                if (HttpContext.Current != null && HttpContext.Current.Session != null)
                {
                    HttpContext.Current.Session["SignedInUser"] = user;
                }
            }

            public static User GetUserFromSession()
            {
                User user = null;
                if (HttpContext.Current != null && HttpContext.Current.Session != null)
                {
                    user = (User) HttpContext.Current.Session["SignedInUser"];
                }
                return user;
            }

However, when i refresh the page at the same very moment after login, my session is coming back as null. In this case Request.IsAuthenticated is true and User.Identity.Name has my user name in it.

I have the following in the web.config as well.

What am i missing here?

Here is the full web.config. Either i am missing something from the web.config or something is interfering with my session.

<?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=301880
  -->
<configuration>
  <!-- Move site specific app settings to their own environment config file inside Configs folder. Keep common settings here -->
  <appSettings file="Configs\AppSettings_CurrentSprint.config">
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>


  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />

    <machineKey validationKey="" validation="SHA1" decryption="AES" />

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

    <authentication mode="Forms">
      <forms loginUrl="~/EPT/Home" name="SalesSupport.ASPXFORMSAUTH" enableCrossAppRedirects="true" timeout="20" slidingExpiration="true" />
      <!-- timeout="600" -->
    </authentication>
    <membership>
      <providers>
        <clear />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
      </providers>
    </profile>

    <customErrors mode="Off" />

    <pages>
      <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.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="System.Web.Optimization" />


      </namespaces>
    </pages>

  </system.web>

  <system.webServer>
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <!--Had to set this for it to work on IIS 7-->
    <modules runAllManagedModulesForAllRequests="true" />

    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <staticContent>
      <!--Required to get IIS to compress javascript files-->
      <remove fileExtension=".js" />
      <mimeMap fileExtension=".js" mimeType="text/javascript" />
    </staticContent>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
learning...
  • 3,104
  • 10
  • 58
  • 96
  • Can you explain what you mean by create session via ajax? Are you using Ajax.BeginForm or $Ajax Post or Get? Session is created by the server on the first request. You may be adding objects to the session. It is possible to request a resource using ajax get that does not refresh or create session state, like requesting an image, except you have a valid authentication ticket so the response will likely be a 200 status code. An easy test would be to put a breakpoint on your server side function that gets called and watch what comes back on the client using the F12 debugger. – Ross Bush Nov 06 '14 at 22:47
  • I am doing a standard $.ajax form post. The http post action authenticates the user, gets the user info, puts the user info in the session and then sends the success response to the ajax call. Since this is success, ajax refreshes the page. It is on refresh that my session is null. Now if i put some thing in the session via standard actions then they are available to me. – learning... Nov 06 '14 at 22:52
  • Is your controller method being cached perhaps so that the refresh is not making a round trip after all? – Ross Bush Nov 06 '14 at 22:56
  • Found the solution but i am still looking for "why"... I needed to remove and add the session. This post helped http://stackoverflow.com/questions/10629882/asp-net-mvc-session-is-null – learning... Nov 06 '14 at 23:31

0 Answers0