应无所住,而生其心
排名
1
文章
860
粉丝
112
评论
163
net core webapi post传递参数
庸人 : 确实坑哈,我也是下班好了好几次,发现后台传递对象是可以的,但...
百度编辑器自定义模板
庸人 : 我建议换个编辑器,因为现在百度富文本已经停止维护了,用tinymec...
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

Net Core中使用cookie

9924人阅读 2019/1/9 22:44 总访问:5182176 评论:7 收藏:0 手机
分类: .NET Core

net core中可以使用传统的cookie也可以使用加密的cookie


NET CORE中使用传统cookie


设置:  

  1.  HttpContext.Response.Cookies.Append("password","123456");

获取:

  1.  string value = "";
  2.  HttpContext.Request.Cookies.TryGetValue("password"out value);

删除

  1.  HttpContext.Response.Cookies.Delete("password");

 


传统的Cookie是用的明文传递的:


 NET CORE中使用加密cookie


1:使用nuget命令下载依赖            

    Install-PackageMicrosoft.AspNetCore.Authentication.Cookies             

    注:添加过后重新生成一下,不然没有提示,强制写出来也会提示报错


2:在startup.cs中注册   

  1.      app.UseCookieAuthentication(new CookieAuthenticationOptions() {
  2.  
  3.                 AuthenticationScheme="myuser"//名称
  4.                 AutomaticAuthenticate=true,//自动验证
  5.                 LoginPath= "/account/login"//登录地址
  6.             });

3:创建验证登录方法(写入cookie)             

  1.  public async Task<IActionResult> ExeLogin()
  2.         {
  3.  
  4.             int userid = 1;
  5.             string username = "xp";
  6.  
  7.             ClaimsIdentity identity = new ClaimsIdentity("Forms");
  8.             identity.AddClaim(new Claim(ClaimTypes.Sid, userid.ToString()));
  9.             identity.AddClaim(new Claim(ClaimTypes.Name, username));
  10.             identity.AddClaim(new Claim("password""123456"));//自己随便写一个名字
  11.  
  12.             var principal = new ClaimsPrincipal(identity);
  13.             await HttpContext.Authentication.SignInAsync("myuser", principal, new AuthenticationProperties { IsPersistent = true });
  14.  
  15.             //登录后需要返回的页面
  16.             //string returnUrl = Request.Query["returnUrl"];
  17.             //if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
  18.  
  19.             return RedirectToAction("index""account");
  20.         }


4:获取加密cookie的方法            

  1.  [Authorize(ActiveAuthenticationSchemes = "myuser")]
  2.         public IActionResult Index()
  3.         {
  4.             //用户用户信息
  5.             var userId = User.FindFirst(ClaimTypes.Sid).Value;
  6.             var userName = User.Identity.Name;
  7.  
  8.             //获取用户名方法2
  9.             string username2 = User.FindFirst(ClaimTypes.Name).Value;
  10.             //获取名字叫password的值
  11.             string password = User.FindFirst("password").Value;
  12.  
  13.  
  14.             ViewBag.userId = userId;
  15.             ViewBag.username = username2;
  16.  
  17.             return View();
  18.         }

 注:使用如下特性可以在用户没有登录得时候请求登录方法(Controller与action都适用)

 [Authorize(ActiveAuthenticationSchemes="myuser")]


 5:退出登录方法(删除cookie)       

  1.    public async Task<IActionResult> Exit()
  2.         {
  3.             await HttpContext.Authentication.SignOutAsync("myuser");   // Startup.cs中配置的验证方案名
  4.  
  5.             return RedirectToAction("index""home");
  6.         }

  可以看到cookie是加密后的


NET CORE中配合控制器使用加密cookie

在过滤器中限制除了登录本身都需要登录后才能访问

  1.     public class IsLoginFilter:ActionFilterAttribute
  2.     {     
  3.         public override void OnActionExecuting(ActionExecutingContext context)
  4.         {
  5.             string controller = context.RouteData.Values["controller"].ToString();
  6.             string action = context.RouteData.Values["action"].ToString();
  7.  
  8.             if (controller.ToLower() == "account")//忽略登录本身
  9.                 return;
  10.  
  11.  
  12.             //检查是否登录
  13.             var  sid = context.HttpContext.User.FindFirst(ClaimTypes.Sid);
  14.  
  15.             //表示用户没有登录跳转到登录页
  16.             if (sid == null)
  17.             {
  18.                 context.Result = new RedirectResult("/account/login");
  19.             }
  20.  
  21.         }
  22.     }






欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价

雨雨雨雨辰

2019/1/10 23:57:53

nice

剑轩:@雨雨雨雨辰[握手][握手]

2019/1/11 9:51:03 回复

撸码成魔

2019/1/11 10:26:49

哎哟 不错唷。

剑轩:@撸码成魔为什么不是来着北方的狼呢[斜眼笑]

2019/1/11 11:20:58 回复

liujy

2019/1/11 16:07:20

哈哈

2019/1/11 22:49:12 回复

2019/1/11 22:49:14 回复

net core 使用 EF Code First

下面这些内容很老了看这篇:https://www.tnblog.net/aojiancc2/article/details/5365 项目使用多层,把数据库访问...

.net mvc分部页,.net core分部页

.net分部页的三种方式第一种:@Html.Partial(&quot;_分部页&quot;)第二种:@{ Html.RenderPartial(&quot;分部页&quot;);}...

StackExchange.Redis操作redis(net core支持)

官方git开源地址https://github.com/StackExchange/StackExchange.Redis官方文档在docs里边都是官方的文档通过nuget命令下...

.net core 使用session

tip:net core 2.2后可以直接启用session了,不用在自己添加一次session依赖,本身就添加了使用nuget添加引用Microsoft.AspN...

通俗易懂,什么是.net?什么是.net Framework?什么是.net core?

朋友圈@蓝羽 看到一篇文章写的太详细太通俗了,搬过来细细看完,保证你对.NET有个新的认识理解原文地址:https://www.cnblo...

asp.net core2.0 依赖注入 AddTransient与AddScoped的区别

asp.net core主要提供了三种依赖注入的方式其中AddTransient与AddSingleton比较好区别AddTransient瞬时模式:每次都获取一...

.net core 使用 Kestrel

Kestrel介绍 Kestrel是一个基于libuv的跨平台web服务器 在.net core项目中就可以不一定要发布在iis下面了Kestrel体验可以使...

net core项目结构简单分析

一:wwwrootwwwroot用于存放网站的静态资源,例如css,js,图片与相关的前端插件等lib主要是第三方的插件,例如微软默认引用...

net core使用EF之DB First

一.新建一个.net core的MVC项目新建好项目后,不能像以前一样直接在新建项中添加ef了,需要用命令在添加ef的依赖二.使用Nug...

.net core使用requestresponse下载文件下载excel等

使用request获取内容net core中request没有直接的索引方法,需要点里边的Query,或者formstringbase64=Request.Form[&quot;f...

iframe自适应高度与配合net core使用

去掉iframe边框frameborder=&quot;0&quot;去掉滚动条scrolling=&quot;no&quot;iframe 自适应高度如果内容是固定的,那么就...

net core启动报错Unable to configure HTTPS endpoint. No server certificate was specified

这是因为net core2.1默认使用的https,如果使用Kestrel web服务器的话没有安装证书就会报这个错其实仔细看他的错误提示,其...

net core中使用url编码与解码操作

net core中暂时还没有以前asp.net与mvc中的server对象。获取url的编码与解码操作不能使用以前的server对象来获取。使用的是...

下载net core

官方下载地址:https://dotnet.microsoft.com/download 进来之后就可以看到最新的下载版本可以直接点击下载,也可以下载其...

net core使用依赖注入来装载EF的上下文对象

妹子情人节快乐~.net core中用了不少的依赖注入,官方文档中也推荐使用。这样使用依赖注入来管理ef对象,还是比较科学,比如...