4_Cookie
action里使用Cookie
设置值
HttpContext.Response.Cookies.Append("userName2", "华哥");
读取
string un;
HttpContext.Request.Cookies.TryGetValue("userName2", out un);
配合权限过滤器进行登录验证
创建好权限过滤器
namespace MyFirstNetCore.Filter
{
//权限筛选器
public class MyAuthorFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//判断是否需要跳过权限验证筛选器
if (HasAllowAnonymous(context))
return;//跳过权限验证
//获取cookie
string userName = "";
context.HttpContext.Request.Cookies.TryGetValue("userName",out userName);
if (string.IsNullOrWhiteSpace(userName))
context.Result = new RedirectToActionResult("index","login",null);
}
//用于判断Action或控制器有没有AllowAnonymous标签,微软写的
private bool HasAllowAnonymous(AuthorizationFilterContext context)
{
var filters = context.Filters;
for (var i = 0; i < filters.Count; i++)
{
if (filters[i] is IAllowAnonymousFilter)
{
return true;
}
}
var endpoint = context.HttpContext.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
{
return true;
}
return false;
}
}
}
创建一个LoginController控制器,加上绕过权限过滤器特性
[AllowAnonymous]//绕过权限过滤器
public class LoginController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Execlogin(string userName)//验证
{
//写入一个cookie
HttpContext.Response.Cookies.Append("userName",userName);
return RedirectToAction("index","home");
}
}
Login/index的视图
在Startup类的ConfigureServices方法里注入权限过滤器
这样,只要不输入文本框的值,就无法访问其它控制器