.net 注册session

100 阅读1分钟

背景

控制器

using Microsoft.AspNetCore.Mvc;

namespace WebApplication3.Controllers
{
    public class FirstController : Controller
    {
        public IActionResult Index()
        {
           
            ViewBag.User1 = "张三";
            ViewData["User2"] = "李四";
            TempData["User3"] = "wangwu";
            HttpContext.Session.SetString("User4", "zhaoliu");
            Object User5 = "tianqi";

            return View(User5);
        }
    }
}


视图


@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>
<h2>User1=@ViewBag.User1</h2>
<h2>User2=@ViewData.["User2"]</h2>
<h2>User3=@TempData["User3"]</h2>
<h2>User4=@Context.Session.GetString("User4")</h2>
<h2>User5=@Model</h2>

运行后报错

image.png

解决策略

分别添加

builder.Services.AddSession();
app.UseSession();

image.png

修改后重新运行成功

image.png