var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), true, JsonConvert.SerializeObject(userinfo), FormsAuthentication.FormsCookiePath); HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), null); var hash = FormsAuthentication.Encrypt(ticket); CookieHelper.SetCookie(FormsAuthentication.FormsCookieName, hash, FormsAuthentication.FormsCookiePath, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), true, FormsAuthentication.RequireSSL);
using System; using System.Web.Mvc; using System.Web.Routing; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.Request.IsAuthenticated) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Login" })); } else { base.HandleUnauthorizedRequest(filterContext); } } }
filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary( new { controller = "Login", action = "Login", returnUrl = filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) }));