我正在尝试在asp.net-mvc5项目中保存有关HttpContext.Current.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:
在网络配置中,我有:
<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>
答案 0 :(得分:1)
我假设你错过了覆盖global.asax中的FormsAuthentication_OnAuthenticate方法 查看此示例以获取解决方案 http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF