2016-04-05 10 views
0

Ich versuche, Informationen über die Anmeldung in der HttpContext.Current.User.Identity in einem asp.net-MVC5-Projekt zu speichern. Aber immer ist leer.MVC Anmeldung. User.Identity immer leer

Erste von allen, ein Blick mit Controller. Wenn Sie auf Login-Button klicken, um den Controller rufen:

public ActionResult Button1_Click(string user, string pass) 
{ 
    bool result = _model.ValidateLogin(user, pass, 3, false); 

    DirectResult r = new DirectResult(); 

    // Do some Authentication... 
    if (!result) 
    { 
     r.Success = false; 
     r.ErrorMessage = "Invalid username or password."; 
    } 

    return r; 
} 

Verfahren ValidateLogin, überprüfen Sie zuerst die Benutzer-Datenbank ist, und mit der ID ein Cookie erstellen:

DateTime now = DateTime.Now; 
System.Web.Security.FormsAuthentication.Initialize(); 
System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, userId.ToString(), now, now.Add(System.Web.Security.FormsAuthentication.Timeout), checkRemember, string.Empty, System.Web.Security.FormsAuthentication.FormsCookiePath); 
string hash = System.Web.Security.FormsAuthentication.Encrypt(ticket); 
System.Web.HttpCookie cookie = new System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, hash); 
if (ticket.IsPersistent) 
cookie.Expires = now.AddYears(1); 
System.Web.HttpContext.Current.Response.Cookies.Add(cookie); 

Aber wenn ich versuchen Sie, den Benutzer zu überprüfen.Identify ist immer leer und "IsAuthenticated" ist falsch:

Warum? Irgendeine Idee?

bearbeiten für Add web.config:

Im Web-Config, ich habe:

<authentication mode="Forms"> 
     <forms loginUrl="~/Login/Index" protection="All" timeout="120" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.html" cookieless="UseDeviceProfile" enableCrossAppRedirects="false"/> 
</authentication> 
<authorization> 
     <deny users="?"/> 
</authorization> 
<location path="Login"> 
     <system.web> 
      <authorization> 
       <allow users="*"/> 
      </authorization> 
     </system.web> 
</location> 

Antwort