步骤一: 在Startup 文件中做相应的设置
ConfigureServices方法里添加
代码语言:javascript复制//ConfigureServices添加:
services.AddSession(options =>
{
options.Cookie.Name = ".AdventureWorks.Session";
options.IdleTimeout = System.TimeSpan.FromSeconds(120);//设置session的过期时间
options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
});
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
#region 跨域
services.AddCors(options =>
options.AddPolicy("AllowSameDomain",
builder => builder.WithOrigins().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
#endregion
Configure方法里面添加
代码语言:javascript复制app.UseSession();//UseSession配置在UseMvc之前
二 在具体的Control配置相应数据
1. 配置 并获取httpcontext
示例:
代码语言:javascript复制public class HomeController : Controller
{
private IHttpContextAccessor _accessor;
public HomeController(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public IActionResult Index()
{
var httpcontext = _accessor.HttpContext;
return View();
}
}
2. 写SessionHelper类
代码语言:javascript复制 public class SessionHelper
{
private IHttpContextAccessor _accessor;
private ISession _session ;
private IRequestCookieCollection _requestCookie ;
private IResponseCookies _responseCookie;
public SessionHelper(HttpContext context)
{
_session = context.Session;
_requestCookie = context.Request.Cookies;
_responseCookie = context.Response.Cookies;
}
/// <summary>
/// 设置session值
/// </summary>
/// <param name="session"></param>
/// <param name="key">键</param>
/// <param name="value">值</param>
public void SetSession(string key, string value)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(value);
_session.Set(key, bytes);
}
/// <summary>
/// 获取Session值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetSession(string key)
{
Byte[] bytes;
_session.TryGetValue(key, out bytes);
var value = System.Text.Encoding.UTF8.GetString(bytes);
if (string.IsNullOrEmpty(value))
{
value = string.Empty;
}
return value;
}
///// <summary>
///// 设置本地cookie
///// </summary>
///// <param name="key">键</param>
///// <param name="value">值</param>
///// <param name="minutes">过期时间</param>
//public void SetCookies(string key,string value,int day = 1)
//{
// _responseCookie.Append(key, value, new CookieOptions
// {
// Expires = DateTime.Now.AddDays(day)
// }) ;
//}
//public void DeleteCookies(string key)
//{
// _responseCookie.Delete(key);
//}
//public string GetCookiesValue(string key)
//{
// _requestCookie.TryGetValue(key, out string value);
// if (string.IsNullOrEmpty(value))
// {
// value = string.Empty;
// }
// return value;
//}
}
3. 方法里调用sessionHelper
代码语言:javascript复制 var httpContext = _accessor.HttpContext;
SessionHelper session = new SessionHelper(httpContext);
string key = "王明";
string value = "2020年 大运年";
//设置session值
session.SetSession(key, value);
//获取session值
session.GetSession(key);