public IActionResult Main() { var user = _HttpContextAccessor.HttpContext.Session.Get <HQuser>("user"); if (user == null) { user = new HQuser(); user.account = "没登入"; } return(View(user)); }
// GET: Home public ActionResult Main() { code.HQuser user = null; if (this.Session["user"] != null) { user = (HQuser)this.Session["user"]; } else { user = new HQuser(); } return(View(user)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddHttpContextAccessor(); services.AddSession(); ///添加路由 services.AddRouting(); //////////// ///设置登入共享参数 /////////////// services.AddAuthentication(HQAuthenticationHandlerOptions.HQAuthenticationName)///这个很重要,要和mvc的保持一致 .AddHQAuthentication2((options, CookieOption) => { options.HasLoginEvent +=// class1.loginFun; () => { var httpContextAccessor = services.BuildServiceProvider().GetService <IHttpContextAccessor>(); var v1 = httpContextAccessor.HttpContext.Session.Get <HQuser>("user"); if (v1 == null) { return(""); } Console.WriteLine("AddHQAuthentication2 HasLogin "); return(v1.account); }; options.LoginEvent += o => { HQuser User = new HQuser() { account = o, password = o, id = 1 }; var httpContextAccessor = services.BuildServiceProvider().GetService <IHttpContextAccessor>(); httpContextAccessor.HttpContext.Session.Set <HQuser>("user", User); Console.WriteLine("AddHQAuthentication2 Login "); }; options.LogOutEvent += () => { var httpContextAccessor = services.BuildServiceProvider().GetService <IHttpContextAccessor>(); httpContextAccessor.HttpContext.Session.Set <HQuser>("user", null); Console.WriteLine("AddHQAuthentication2 LogOut "); }; options.Domain = "hqbuy.com"; CookieOption.AccessDeniedPath = "/home/index?LoginMsg=AccessDeniedPath"; CookieOption.LoginPath = "/home/index?LoginMsg=LoginPath"; CookieOption.LogoutPath = "/home/index?LoginMsg=LogoutPath"; CookieOption.ExpireTimeSpan = new TimeSpan(0, 5, 0); }); }