简体   繁体   English

Angular + ASP.NET MVC4 Session始终为null

[英]Angular + ASP.NET MVC4 Session always null

I am developing a SPA in angular which is running within nginx server and an ASP.NET MVC4 web app that runs in IIS server provides some API functions to angular app. 我正在开发一个在nginx服务器中运行的角度缓冲区,并且在IIS服务器中运行的ASP.NET MVC4 Web应用程序为角度应用程序提供了一些API函数。 As soon as user logins some data need to be kept in httpsession( Assume I don't want to use angular's session storage). 一旦用户登录,一些数据需要保存在httpsession中(假设我不想使用angular的会话存储)。 But the session is always returns null, even I stored some data after successful login. 但是会话总是返回null,即使我在成功登录后存储了一些数据。 Please have a look on some of the necessary code. 请查看一些必要的代码。

authservice.js authservice.js

login: function (email, password) {
     var deferred = $q.defer();
     $http({
          url: global.API_URL + '/Auth/Login',
          method: 'POST',
                data: { email: email, password: encodeURIComponent(password)}
   }).then(function (response) {
       if (response.data.code == 0) {
          //If success go to home
});

AuthController.js AuthController.js

    [ActionName("Login")]
    [HttpPost]
    public JsonResult Index(string email, string password)
    {
    CustResponse response = new CustResponse ();
    //Get the logged in user data
     User user = userService.GetUser(email);   

    //Get the hash 
    string hash = PasswordUtil.CreatePasswordHash(user.Salt, password);

    //Custom membership provider
    CustMembershipProvider provider = new CustMembershipProvider();
    bool isValid = provider.ValidateUser(email, hash); 

//Store the user token into the session
  System.Web.HttpContext.Current.Session["TOKEN"] = //Some token value;

    //if valid send response code 0
    response.code = 0;
    response.message = "Success";
    response.data = isValid ;

    return Json(response);
    }

The token is getting stored into the session as i can see it in the session object when I am in AuthController. 令牌存储到会话中,因为当我在AuthController中时,我可以在会话对象中看到它。

AwmsMembershipProvider.cs AwmsMembershipProvider.cs

 public class CustMembershipProvider : MembershipProvider
    {
        public override bool ValidateUser(string email, string hash)
        {
            bool isValid = false;
            using (var db = new AwmsContext())
            {
               User user = db.Users.SingleOrDefault(a => a.Email == email);
               if (user != null && user.PasswordHash != null &&            user.PasswordHash.Equals(hash))
              {
                  isValid = true;
               }
            }
            return isValid;
        }

WebConfig.xml WebConfig.xml

 <?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=152368
  -->
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-AWMS-20160710224309;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-AWMS-20160710224309.mdf" />
    <add name="AwmsContext" connectionString="metadata=res://*/awms.csdl|res://*/awms.ssdl|res://*/awms.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;initial catalog=AWMS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="LogFilePath" value="./App_Data/Config/Log.xml" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="20" />
    </authentication>    
    <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.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <clear/>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="AwmsMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add name="AwmsMembershipProvider" type="Awms.Dal.Provider.AwmsMembershipProvider" />
      </providers>
    </membership>
    <roleManager defaultProvider="EmblaRoleProvider">
      <providers>
        <clear />
        <add name="EmblaRoleProvider" type="Awms.Dal.Provider.AwmsRoleProvider" />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider" timeout="20" cookieless="false">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
       <httpProtocol>
        <customHeaders>
          <clear />
          <add name="Access-Control-Allow-Origin" value="http://localhost:8085" />
        </customHeaders>
    </httpProtocol>

  <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></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

Once the user is logged in he's being redirected to home page and he need to access some of the previously stored session variables from another controller. 一旦用户登录,他就被重定向到主页,并且他需要从另一个控制器访问一些先前存储的会话变量。

 public JsonResult GetRoles()
        {
               String token = (String)System.Web.HttpContext.Current.Session["TOKEN"];
.....
}

When I am doing so it's always null. 当我这样做时,它总是为空。 Am I doing anything wrong here. 我在这做错了吗? Please feel free to provide your valuable ideas 请随时提供您宝贵的意见

looks you need to enable cookies. 看起来你需要启用cookie。 see details on below artical 看下面的艺术细节

https://gregorybeamer.wordpress.com/2012/11/04/session-and-cookies-in-asp-net-mvc-oh-my/ https://gregorybeamer.wordpress.com/2012/11/04/session-and-cookies-in-asp-net-mvc-oh-my/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM