2016-09-13 3 views
1

Я разрабатываю SPA в угловом режиме, который работает на сервере nginx, и веб-приложение ASP.NET MVC4, которое работает на сервере IIS, предоставляет некоторые функции API для углового приложения. Как только пользователь войдет в систему, некоторые данные должны быть сохранены в httpsession (предположим, что я не хочу использовать хранилище сессий углов). Но сессия всегда возвращает null, даже я сохранил некоторые данные после успешного входа в систему. Пожалуйста, ознакомьтесь с некоторыми из необходимого кода.Угловая + ASP.NET MVC4 Сессия всегда null

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

[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); 
    } 

Маркер становится хранится в сессии, как я могу видеть его в объект сессии, когда я нахожусь в AuthController ,

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

<?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> 

После того, как пользователь вошел в систему, он перенаправляется на главную страницу, и он должен получить доступ к некоторым из ранее сохраненное переменные сеанса от другого контроллера.

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

Когда я делаю так, это всегда равно нулю. Я делаю что-то неправильно здесь. Пожалуйста, не стесняйтесь предлагать свои ценные идеи

+0

Я не вижу никакого кода, где этот ключ частности сессии на самом деле * набор *, или на самом деле, где вообще ничего, что делается с сессией, прежде чем пытаться получить значение из него. –

+0

Жаль, что он был там, но из-за проблемы с форматом он может не выделяться вам. Так или иначе, это доступно сейчас –

+0

Неправильно ли вставлен ваш web.config? Это выглядит неправильно. – Amy

ответ

Смежные вопросы