HttpContext.User.Identity.Name有时是空的

时间:2016-10-25 01:44:16

标签: c# asp.net-mvc owin

我在ASP.NET MVC 5中使用OWIN进行身份验证。

我的项目在IIS Express的localhost中完美运行。问题是我在Web服务器上传项目时。

我登录并且应用程序工作正常。然后,好像会话已经过期了。 HttpContext.User.Identity.Name为空。

这是我的动作过滤器:

public override void OnActionExecuting(ActionExecutingContext context)
{            
    if (string.IsNullOrEmpty(context.HttpContext.User.Identity.Name))
    {
        context.Result = new RedirectResult("authentication");
        return;
    }
}

这是我的登录

 public JsonResult Login(LoginModel input)
    {
        if (ModelState.IsValid)
        {
            if(_AuthenticationLogica.ChecarUsuario(input.User, input.Pass))
            {
                int idUser = _AuthenticationLogica.GetIdUser(input.User);
                var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, input.Usuario), new Claim(ClaimTypes.Sid, idUsuario+"") },DefaultAuthenticationTypes.ApplicationCookie,ClaimTypes.Name, ClaimTypes.Role);
                foreach (var item in _UsuariosLogica.GetPermissionUser(idUser))
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, item.IdDerecho + ""));
                }
                var claimsPrincipal = new ClaimsPrincipal(identity);
                // Set current principal
                Thread.CurrentPrincipal = claimsPrincipal;
                // if you want roles, just add as many as you want here (for loop maybe?)
                identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
                // tell OWIN the identity provider, optional
                // identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));
                int id = _AuthenticationLogica.ObtenerIdUsuario("jcsoto");
                Authentication.SignIn(new AuthenticationProperties
                {
                    IsPersistent = true
                }, identity);

                FormsAuthentication.SetAuthCookie(input.Usuario, true);
                return Json(new { Resultado = 0, Mensaje = "Ready", IdUser = idUser });
            }
        }

        return Json(new { Resultado = 1, Mensaje = "User or pass wrong" });
    }

0 个答案:

没有答案