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

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

因此我无法了解会话结束时我们如何注销用户…

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") }); } 

为此,您需要定义一个ActionFilter属性,您需要将用户重定向到相应的控制器操作。 在那里你需要检查会话值,如果它是null,那么你需要重定向用户。 以下是代码( 您也可以访问我的博客了解详细信息 ):

 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" })); } } } } } 

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

 AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 

Session_End()的调用导致exception。 这完全是预期的,因为你不能简单地创建new AccountController() ,调用accountController.SignOut()并期望它工作。 这个新的控制器没有连接到MVC管道 – 它没有HttpContext和所有其他要求能够工作。

您应该将用户注销以响应他们所做的请求。 使用个人帐户身份validation创建新的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; } } 

希望这可以帮助。

我尝试了这一切:

 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); 

校验

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

“`

这对我有用

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

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

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