分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

asp.net core session的使用

发布时间:2023-09-06 01:54责任编辑:胡小海关键词:暂无标签

Session介绍

本文假设读者已经了解Session的概念和作用,并且在传统的.net framework平台上使用过。

Asp.net core 1.0好像需要单独安装,在nuget控制台,选择你的web项目执行以下命令:

Install-Package Microsoft.AspNetCore.Session

如果需要卸载,在nuget控制台,选择具体项目,执行以下命令:

Uninstall-Package Microsoft.AspNetCore.Session

Asp.net core 2.0已经集成了Session组件,无需单独安装。

Asp.net core中的session使用方法跟传统的asp.net不一样,它内置了两个方法供我们调用:

void Set(string key, byte[] value);bool TryGetValue(string key, out byte[] value);

这两个方法的第一个参数都是key,第二个参数都是value,且value是一个byte[]类型的数据。所以在使用的时候,我们还需要做转换,使用起来很不方便。

针对这一点,session提供了扩展方法,但是需要引用Microsoft.AspNetCore.Http命名空间。然后再使用扩展方法:

public static byte[] Get(this ISession session, string key);public static int? GetInt32(this ISession session, string key);public static string GetString(this ISession session, string key);public static void SetInt32(this ISession session, string key, int value);public static void SetString(this ISession session, string key, string value);

使用方法如下:

HttpContext.Session.SetString("password", "123456");var password = HttpContext.Session.GetString("password");

简单使用

打开Startup.cs文件

1.在ConfigureServices方法里面添加:

services.AddSession();

2.在Configure方法里面添加:

app.UseSession();

3.新建控制器SessionController,添加如下代码:

 ???????/// <summary> ???????/// 测试Session ???????/// </summary> ???????/// <returns></returns> ???????public IActionResult Index() ???????{ ???????????var username = "subendong"; ???????????var bytes = System.Text.Encoding.UTF8.GetBytes(username); ???????????HttpContext.Session.Set("username", bytes); ???????????Byte[] bytesTemp; ???????????HttpContext.Session.TryGetValue("username", out bytesTemp); ???????????var usernameTemp = System.Text.Encoding.UTF8.GetString(bytesTemp); ???????????//扩展方法的使用 ???????????HttpContext.Session.SetString("password", "123456"); ???????????var password = HttpContext.Session.GetString("password"); ???????????var data = new { ???????????????usernameTemp, ???????????????password ???????????}; ???????????return Json(data); ???????}

4.F5运行,输入地址:http://localhost/session,即可查看正确输出:

{"usernameTemp":"subendong","password":"123456"}

5.如果第一步和第二步不做的话,直接使用session,会报错:

InvalidOperationException: Session has not been configured for this application or request

asp.net core session的使用

原文地址:https://www.cnblogs.com/subendong/p/9052590.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved