Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 角度+;ASP.NET MVC4会话始终为空_C#_Asp.net_Angularjs_Asp.net Mvc 4_Session - Fatal编程技术网

C# 角度+;ASP.NET MVC4会话始终为空

C# 角度+;ASP.NET MVC4会话始终为空,c#,asp.net,angularjs,asp.net-mvc-4,session,C#,Asp.net,Angularjs,Asp.net Mvc 4,Session,我正在angular中开发一个SPA,它在nginx服务器中运行,在IIS服务器中运行的ASP.NET MVC4 web应用程序为angular应用程序提供一些API函数。一旦用户登录,一些数据就需要保存在httpsession中(假设我不想使用angular的会话存储)。但是会话总是返回null,即使我在成功登录后存储了一些数据。请看一些必要的代码 authservice.js login: function (email, password) { var deferred = $q

我正在angular中开发一个SPA,它在nginx服务器中运行,在IIS服务器中运行的ASP.NET MVC4 web应用程序为angular应用程序提供一些API函数。一旦用户登录,一些数据就需要保存在httpsession中(假设我不想使用angular的会话存储)。但是会话总是返回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
});
    [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);
    }
 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;
        }
AuthController.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
});
    [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);
    }
 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;
        }
当我在AuthController中时,我可以在会话对象中看到令牌被存储到会话中

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

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

当我这样做时,它总是空的。我做错什么了吗。请随时提供启用Cookie所需的宝贵意见。详见下文


看起来您需要启用Cookie。详见下文


我看不到任何代码实际设置了特定的会话密钥,或者在您尝试从会话中检索值之前正在对会话执行任何操作。很抱歉,它在那里,但由于格式问题,它可能无法突出显示给您。不管怎样,它现在可用。您的web.config是否粘贴错误?它看起来不正确。我没有提供整个web.config。如果你愿意,我可以提供。注意,我把那些点放在我注意到的地方。我之所以提起它,是因为
节点看起来没有正确关闭。只是仔细检查粘贴是否正确。我看不到任何代码实际设置了特定的会话密钥,或者在您尝试从会话中检索值之前正在对会话执行任何操作。很抱歉,它确实存在,但由于格式问题,它可能无法向您突出显示。不管怎样,它现在可用。您的web.config是否粘贴错误?它看起来不正确。我没有提供整个web.config。如果你愿意,我可以提供。注意,我把那些点放在我注意到的地方。我之所以提起它,是因为
节点看起来没有正确关闭。只是再检查一下,确认它不是一个坏的浆糊。