如何在 dot net core 中使用 Session?
我想在用戶登錄時使用會話標簽來存盤用戶 ID 和用戶名。我正在使用 .net 核心版本 3.1 我創建了一個帳戶控制器,并且在登錄(發布方法)中我正在嘗試使用會話標簽。這是 AccountController.cs 中的登錄方法
//POST Login
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Login(Account user)
{
if(ModelState.IsValid)
{
var obj = _db.Accounts.Where(u => u.Name.Equals(user.Name) && u.Password.Equals(user.Password)).FirstOrDefault();
if(obj != null)
{
Session["Id"] = obj.Id.ToString(); // Error : The name 'Session' does not exist in the current context
Session["Name"] = obj.Name.ToString(); // Error : The name 'Session' does not exist in the current context
return RedirectToAction("Index", "Home");
}
}
return View(user);
}
我還使用了 ConfigureServices 中的 services.AddSession() 和 Startup.cs 檔案中 Configure 中的 app.UseSession() 在 Startup.cs 中配置服務
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddControllersWithViews();
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
}
在 Startup.cs 中配置
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
//app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
我該如何解決這個問題?
uj5u.com熱心網友回復:
你可以使用這樣的東西:
if(obj != null)
{
const string userId = "_UserId";
const string userName = "_UserName";
HttpContext.Session.SetString(userId, obj.Id.ToString());
HttpContext.Session.SetString(userName, obj.Name.ToString());
return RedirectToAction("Index", "Home");
}
您可以使用它來獲取它:
const string userId = "_UserId";
const string userName = "_UserName";
string user = httpContext.Session.GetString(userId);
string name = httpContext.Session.GetString(userName);
編輯#1:TY @Dharman。(使用制表符/空格復制/粘貼 TS)
uj5u.com熱心網友回復:
要Session在 .NET CORE 中設定,您可以參考這個 SO answer。現在關于您關于清除 的問題Session,您可以這樣做:
HttpContext.Session.Clear();
您可以在MSDN上閱讀更多內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/457915.html
標籤:C# asp.net 核心 会议 模型视图控制器 asp.net-core-mvc
上一篇:Yii2中的會話檔案存盤在哪里?
下一篇:從R中的多個資料框中過濾行
