为了账号安全,请及时绑定邮箱和手机立即绑定

ASP.NET CORE中使用SESSION

标签:
C#

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

  1. NUGET包引用 Microsoft.AspNetCore.Session (注:我在mac下用vs for mac做的时候,NUGET根本搜索不了,都需要FQ的,自己搜索了下,加入博客园的NUGET源就可以了,而且也很快:https://nuget.cnblogs.com/v3/index.json
  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 app, IHostingEnvironment 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();
    }

}

}

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
全栈工程师
手记
粉丝
20
获赞与收藏
97

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消