在添加控制器前,先要添加对Session的支持。
code\utils\SessionHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace core_admin.utils
{
public class SessionHelper
{
private HttpContext context;
public SessionHelper(HttpContext context){
this.context = context;
}
public void SetSession(string key, string value)
{
if(!string.IsNullOrEmpty(value)){
context.Session.SetString(key, value);
} else {
context.Session.SetString(key, "");
}
}
public string GetSession(string key)
{
var value = context.Session.GetString(key);
if (string.IsNullOrEmpty(value))
value = "";
return value;
}
}
}
在Program.cs 增加两处地方,
builder.Services.AddSession();
app.UseSession();
完整的Program.cs
using core_admin.utils;
using core_admin.db;
Global_Values.connStr = WebHelper.get_item("connStr");
AutofacConfig.Register();
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSession();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();