如何在OWIN ASP.NET MVC5中注销用户

时间:2014-10-03 16:07:05

标签: c# session asp.net-mvc-5 logout owin

我有一个标准的 AccountController ASP.NET MVC5项目。 当我尝试注销用户时,我遇到错误,因为HttpContextnull。 (我的意思是HttpContext .GetOwinContext()。身份验证为空)

所以我无法了解会话结束时我们如何注销用户...

global.asax 我有这个

protected void Session_Start(object sender, EventArgs e)
{
     Session.Timeout = 3; 
}

protected void Session_End(object sender, EventArgs e)
{
            try
            {
                 var accountController = new AccountController();
                 accountController.SignOut();
            }
            catch (Exception)
            {
            }
}

的AccountController

public void SignOut()
{
      // Even if I do It does not help coz HttpContext is NULL
      _authnManager = HttpContext.GetOwinContext().Authentication;    

    AuthenticationManager.SignOut();


}

private IAuthenticationManager _authnManager;  // Add this private variable


public IAuthenticationManager AuthenticationManager // Modified this from private to public and add the setter
{
            get
            {
                if (_authnManager == null)
                    _authnManager = HttpContext.GetOwinContext().Authentication;
                return _authnManager;
            }
            set { _authnManager = value; }
}

Startup.Auth.cs

 public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                ExpireTimeSpan = TimeSpan.FromMinutes(3),
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
}

6 个答案:

答案 0 :(得分:13)

假设您使用ApplicationCookie存储登录信息。

$('#tstButton').off("click").on('click',function(){
    alert();
});

答案 1 :(得分:9)

Session_End()的调用导致异常。完全可以预料到这一点,因为您不能简单地创建new AccountController(),调用accountController.SignOut()并期望它能够正常运行。这个新的控制器没有连接到MVC管道 - 它没有HttpContext和其他所有要求都可以工作。

您应该将用户注销以响应他们所做的请求。使用个人帐户身份验证创建新的MVC项目。打开 AccountController ,然后查看LogOff()方法:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        return RedirectToAction("Index", "Home");
    }

这里将执行AuthenticationManager.SignOut()以响应/ Account / LogOff处的POST请求。每当这样的请求到达时,ASP.NET / MVC将创建一个AccountController实例并正确初始化它。之后,将调用LogOff方法,您可以在其中实际执行AuthenticationManager.SignOut();

此外,默认情况下,带有Identity的ASP.NET / MVC应用程序在代码的 Helpers 区域中声明 AuthenticationManager ,如下所示:

private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }

希望这有帮助。

答案 2 :(得分:2)

为此,您需要定义一个ActionFilter属性,您需要将用户重定向到相应的控制器操作。在那里你需要检查会话值,如果它是null,那么你需要重定向用户。以下是代码(Also you can visit my blog for detail step):

public class CheckSessionOutAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim();
            string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim();

            if (!actionName.StartsWith("login") && !actionName.StartsWith("sessionlogoff"))
            {
                var session = HttpContext.Current.Session["SelectedSiteName"];
                HttpContext ctx = HttpContext.Current;
                //Redirects user to login screen if session has timed out
                if (session == null)
                {
                    base.OnActionExecuting(filterContext);


                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Account",
                        action = "SessionLogOff"
                    }));

                }
            }

        }

    }
}

答案 3 :(得分:2)

我尝试了所有这些:

System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
FormsAuthentication.SignOut();
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

Request.GetOwinContext().Authentication.SignOut();

Request.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

但最后这解决了我的问题:

HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty),null);

Check

答案 4 :(得分:2)

Session.Abandon();
var owinContext = System.Web.HttpContext.Current.Request.GetOwinContext();
var authenticationTypes = owinContext.Authentication.GetAuthenticationTypes();
owinContext.Authentication.SignOut(authenticationTypes.Select(o => o.AuthenticationType).ToArray());

```

答案 5 :(得分:1)

这对我有用

`public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;
        authenticationManager.SignOut(AuthenticationType);
    }
`

我遇到的唯一问题是没有重定向到登录,所以我得到一个未找到视图错误,因为我注销的视图是在[Authorize]属性下。我认为当用户未被此代码块授权时内置了自动重定向...

`app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "ApplicationCookie",
        LoginPath = new PathString("/Account/Login"),
        ExpireTimeSpan = TimeSpan.FromHours(1),
    });
`