我嘗試在 ASP.NET Core 6.0 MVC 上使用會話,但無法使其作業,如檔案中所示 - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view= aspnetcore-6.0
我在 program.cs 上添加了會話中間件。
builder.Services.AddSession();
app.UseSession();
在控制器上,我在會話中存盤當前日期時間:
HttpContext.Session.SetString("CurrentDateTime", DateTime.Now.ToString());
直到現在一切都很好。
但問題是當我試影像這樣訪問它的視圖時出現錯誤:
@HttpContext.Session.GetString("CurrentDateTime")
錯誤是:
嚴重性代碼 描述 專案檔案行抑制狀態錯誤(活動) CS0120 非靜態欄位、方法或屬性“HttpContext.Session”需要物件參考UnderstandingControllersViews E:\Yogesh\SEO\Yogihosting\3\UnderstandingControllersViews\UnderstandingControllersViews\視圖\示例\SessionExample.cshtml 2
如何使它作業有人可以幫忙嗎?
uj5u.com熱心網友回復:
您需要將IHttpContextAccessor實作注入您的View并使用它來Session根據需要獲取物件:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
//Get object from session
var mySessionObject= HttpContextAccessor.HttpContext.Session.GetString("CurrentDateTime");
}
<h1>@mySessionObject</h1>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/457056.html
