1:在控制器验证登录成功时存储session与cookie的值
/// <summary>
/// 验证登录 存储Session或Cookie
/// </summary>
/// <returns></returns>
public async Task<IActionResult> ValidateLogin(AdminInfo adminInfo)
{
var result = _adminInfoService.ValidateLogin(adminInfo.LoginName, adminInfo.LoginPwd);
if (result.success)
{
AdminInfo admin = result.data;
//写入Session
HttpContext.Session.Set("Market_Admin", admin);
//写Cookie
var identity = new ClaimsIdentity("Forms"); // 指定身份认证类型
identity.AddClaim(new Claim(ClaimTypes.Sid, admin.AdminId.ToString())); // 用户Id
identity.AddClaim(new Claim(ClaimTypes.Name, admin.LoginName)); // 用户名称
//创建身份证这个证件的携带者:我们叫这个证件携带者为“证件当事人”
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
}
return Json(result);
}
2.写入session时因为自带的方法中没有参数为对象的方法 所以在公共层(Infrastructure)需要添加一个类,在类中自定义方法
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace JiaHua.Market.Infrastructure
{
public static class SessionExtensions
{
#region 存储Session对象
/// <summary>
/// 存储Session对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <param name="key"></param>
/// <param name="value"&