處理 Session 的基本示例

1)首先,在 project.json 中新增依賴項 - "Microsoft.AspNetCore.Session": "1.1.0",

2)在 startup.cs 中新增 AddSession()AddDistributedMemoryCache() 線到 ConfigureServices,就像這樣 -

services.AddDistributedMemoryCache(); //This way ASP.NET Core will use a Memory Cache to store session variables
services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromDays(1); // It depends on user requirements.
            options.CookieName = ".My.Session"; // Give a cookie name for session which will be visible in request payloads.
        });

3)在配置啟動方法中新增 UseSession() 呼叫,如下所示 -

app.UseSession(); //make sure add this line before UseMvc()

4)在 Controller 中,Session 物件可以像這樣使用 -

using Microsoft.AspNetCore.Http;

public class HomeController : Controller
{
    public IActionResult Index()
    { 
        HttpContext.Session.SetString("SessionVariable1", "Testing123");
        return View();
    }

    public IActionResult About()
    {
        ViewBag.Message = HttpContext.Session.GetString("SessionVariable1");

        return View();
    }
}
  1. 如果你正在使用 cors 策略,那麼在啟用
    有關啟用 AllowCredentials 標頭和使用
    WithOrigins 標頭而不是 AllowAllOrigins 的標頭的會話後,有時它可能會出錯。