asp.net core session的使用

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

猜你喜欢

转载自www.cnblogs.com/subendong/p/9052590.html