MVC 5 Forms身份验证为User.Identity.Name返回null

时间:2014-11-10 08:59:21

标签: asp.net-mvc-5 forms-authentication

身份验证无法在我的MVC 5应用程序中对表单身份验证进行身份验证。页面被正确重定向,但User.Identity.IsAuthenticated和User.Identity.Name值为空。

我的webconfig,

  <system.web>        
    <authentication mode="Forms">
          <forms cookieless="UseCookies" defaultUrl="~/" loginUrl="~/user/signin"  name="MYAPPWeb" timeout="21600" slidingExpiration="true"/>
        </authentication>

UserController,

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult SignIn(SignInViewModel user)
        {

                        UserDTO userObj;
                        using (var services = new ServiceFactory())
                        {                            
                            userObj = services.UserManagement.ValidateLoginDetails(ConfigHelper.EnvironmentString, user.TenantName, user.Username, user.Password);
                        }
                                string userID = userObj.UserID.ToString();
                                //FormsAuthentication.RedirectFromLoginPage(userID, user.RememberMe);
                                FormsAuthentication.SetAuthCookie(userID.ToString(),true);

                                FormsAuthentication.RedirectFromLoginPage(userID, false); //DO NOT REMEMBER ME

}

HomeController(默认页面)

 public ActionResult Index()
        {

            bool x = User.Identity.IsAuthenticated; //false?
            string y = User.Identity.Name; //null?

return View();
}

看起来非常直接,我错过了什么?请帮忙!

注意:
  当我创建项目时,我选择了Windows身份验证。它创建了一些与Owin authenticnticaiton相关的配置文件(startup.auth.cs)。我删除了它们并添加了上面的appsetting条目,因为它需要停止加载Owin程序集。

<add key="owin:AutomaticAppStartup" value="false"/>

1 个答案:

答案 0 :(得分:5)

如果您的项目默认具有Owin身份验证,它将从项目中删除表单身份验证。 如果您看到您的网络配置,则可能会看到

<remove name="FormsAuthentication" />

配置。

只需将其删除即可。

我有同样的问题,它解决了这个问题。