MVC登录.User.Identity始终为空



我正试图将有关登录的信息保存在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:

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

我假设您错过了覆盖global.asax中的FormsAuthentication_OnAuthenticate方法签出此示例以获取解决方案http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF

最新更新