ASP.NET CORE中使用SESSION

从 https://www.cnblogs.com/liuxiaoji/p/6860104.html 炒的,这里记到自己博客,以做记录,以后炒也要炒自己博客上的代码,ASP.NET CORE中使用SESSION的步骤如下 :

1. NUGET包引用 icrosoft.AspNetCore.Session
2. Startup.cs中的相应方法加入些代码:

        public void ConfigureServices(IServiceCollection services)
        {
            //添加session
            services.AddDistributedMemoryCache();
            services.AddSession();

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder appIHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession(); //加上这句才能用session

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name"default",
                    template"{controller=Home}/{action=Index}/{id?}");
            });
        }


3. 以下是控制器中使用SESSION的代码,记得要先引用那个命名空间:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using candel.Models;
using Microsoft.AspNetCore.Http; //记得要引用 这个

namespace candel.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.msg = "你好,牛腩,哈哈哈!!!";
            HttpContext.Session.SetString("username""niunan"); //设置SESSION
            return View();
        }

        public IActionResult About(){
            string username = HttpContext.Session.GetString("username"); //获取SESSION
            ViewBag.username = username;
            return View();
        }

 
    }
}

posted @   牛腩  阅读(276)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示