0
我試圖保存在asp.net-mvc5項目中的HttpContext.Current.User.Identity登錄信息。但總是空的。MVC登錄。 User.Identity始終爲空
儘管如此,有一個視圖與控制器。 當你點擊登錄按鈕,呼叫控制器:
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;
}
的方法ValidateLogin,首先檢查用戶數據庫,並與ID創建cookie:
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);
但是,當我嘗試檢查User.Identify始終爲空,「IsAuthenticated」爲假:
protected override System.Security.Principal.IIdentity GetClientIdentity()
{
IIdentity identity = System.Web.HttpContext.Current.User.Identity;
if (identity.IsAuthenticated)
return identity;
else
throw new AuthorizationDeniedException("Not logged in",false);
}
爲什麼?任何想法?
編輯爲附加的web.config:
在web配置,我有:
<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>
只需指出,如果使用版本> = 4,還會列出'Application_PostAuthenticateRequest' –