• net core体系-web应用程序-4net core2.0大白话带你入门-10asp.net core session的使用


    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");

    Session使用

    打开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

    IT黑马
  • 相关阅读:
    SubtextHTTP 模块
    asp.net控件设计时支持(2)自动格式设置
    新立得字体模糊解决经验
    详解新网银木马清除技巧
    Ubuntu 9.10 29日发布,更新列表已经公布
    小样儿想封我?WebOS 1.2.1再次突破iTunes同步限制
    检测到您尚未安装ALEXA工具条
    在Puppy Linux中安装Firefox
    一步一步教你用ES封装系统(最完整视频教程)
    C# 判断是否为数字
  • 原文地址:https://www.cnblogs.com/hmit/p/10767507.html
Copyright © 2020-2023  润新知