Using SESSION in ASP.NET CORE

I made it from https://www.cnblogs.com/liuxiaoji/p/6860104.html, and I wrote it down to my blog here for records. I will also fry the code on my blog in the future. SESSION is used in ASP.NET CORE. Proceed as follows:

 

1. The NUGET package references icrosoft.AspNetCore.Session
2. Add some code to the corresponding method in Startup.cs:

 

        publicvoidConfigureServices(IServiceCollectionservices)        {//添加sessionservices.AddDistributedMemoryCache();services.AddSession();services.AddMvc();        }// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilderappIHostingEnvironmentenv)        {if (env   

            
            
            

            


        
            

            .IsDevelopment())
            {app.UseDeveloperExceptionPage();            }else            {app.UseExceptionHandler("/Home/Error");            }app.UseStaticFiles();app.UseSession(); //加上这句才能用sessionapp.UseMvc(routes =>            {routes.MapRoute(name"default
                

            

                


            

            

            

                
                    ",template"{controller=Home}/{action=Index}/{id?}");            });        }
                    

 

 

 

3. The following is the code that uses SESSION in the controller, remember to reference that namespace first:

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
{publicclassHomeController : Controller    {publicIActionResultIndex()        {ViewBag.msg = "你好,牛腩,哈哈哈!!!";
      

          

            
            HttpContext.Session.SetString("username""niunan"); //设置SESSIONreturnView();        }publicIActionResultAbout(){stringusername = HttpContext.Session.GetString("username"); //获取SESSIONViewBag.username = username;returnView();        }
             


          
             
            
             


 
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326272902&siteId=291194637