一、修改cookie设置
默认,使用cookie存值需要用户同意,改成false去掉限制。 (修改Startup.cs文件)
二、添加跨域设置
修改Startup.cs文件
1.在ConfigureServices方法中,添加
//urls 访问地址 string[] urls = { "http://192.168.1.110:8080", "http://localhost:8080", "http://192.168.1.111:8080" }; //添加跨域访问服务 services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()) );2.在Configure中,添加
// 使用跨域访问服务 app.UseCors("AllowSameDomain");
3.在要跨域的方法或控制器上,添加
[EnableCors("AllowSameDomain")]
三、添加cookies登录认证
修改Startup.cs文件
1.在ConfigureServices方法中,添加
//注册Cookie认证服务, 在mvc注册后面 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
2.在Configure中,添加
// 启用Cookie认证中间件
app.UseAuthentication();
3.登录和取数据的方法
<1>登录
// 有效负载内容 var claims = new[] { new Claim("userName", userName) }; // 存入cookie var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity); Task.Run(async () => { await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, user, new AuthenticationProperties() { IsPersistent = true, // 过期时间60(分钟) ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60), AllowRefresh = true }); }).Wait();<2>取数据
var userName = HttpContext.User.Claims.Where(claim => claim.Type == "userName").First().Value;<3>登出
Task.Run(async () => { // 注销登录的用户,相当于ASP.NET中的FormsAuthentication.SignOut await HttpContext.SignOutAsync(); }).Wait();<4>判断是否登录
if (HttpContext.User.Identity.IsAuthenticated) { // 登录状态 } else { // 未登录 }四、添加过滤器
1.新建一个类,继承Attribute, IActionFilter
2.在Startup.cs中,
<1>全局注册
services.AddMvc(options => { options.Filters.Add(typeof(新建的类名)); });
<2>局部注册
在控制器或action上面添加
[新建的类名]