我開始學習 ASP.NET MVC。現在我嘗試在不使用類 Membership、類 FormsAuthentication等的情況下實作身份驗證功能。我將當前用戶名保存到會話資料中。
要檢查用戶是否已通過身份驗證,我使用以下代碼:
if (!HttpContext.Session.Keys.Contains<string>("authentication")) { // It throws an exception
return RedirectToAction("Login", "Account");
}
此代碼段的第一行拋出例外并顯示以下訊息(我的應用程式顯示訊息和目標站點):
會話未配置。在“Microsoft.AspNetCore.SessionState.HttpSessionState Microsoft.AspNetCore.HttpContext.get_Session()”。
我試過的:
- 將此行添加到我的
Startup.cs:
app.UseSession();
- 不需要打電話
app.UseMvc()。Startup.cs但我嘗試使用它(只是呼叫app.UseMvc()拋出例外。經過一些研究,我在 Stack Overflow 的答案中找到了下面這行):
app.UseMvc(options => options.EnableEndpointRouting = false);
使用
Session.Keys.Contains<string>()而不是HttpContext.Session.Keys.Contains<string>()。但它沒有找到名為 的屬性Session。網上沖浪。我沒有找到任何好的答案。
現在我問我自己的問題。
uj5u.com熱心網友回復:
現在問題解決了。我已將這些片段添加到Startup.cs:
services.AddControllersWithViews();
services.AddMvc(options => options.EnableEndpointRouting = false).AddSessionStateTempDataProvider();
services.AddSession();
和
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseMvcWithDefaultRoute();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537801.html
