ASP.NET核心会话状态 [英] ASP.NET Core Session State

查看:71
本文介绍了ASP.NET核心会话状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,其中有几种方法.在登录方法中,如果登录成功,则启动 HttpContext.Session.SetInt32("ID").该ID是已登录用户的ID.我在许多其他方法中使用此ID进行更多的计算和查询.在每种方法中,我都必须声明一个变量,例如?int userId = HttpContext.Session.GetINT32("ID")可以在该方法中使用此变量.

I have a controller where I have several methods. In the login method, I start a HttpContext.Session.SetInt32("ID"), if the login is successful. This ID is the id of the User logged in. I am using this ID in many other methods to do more calculations and queries. In every method, I have to declare a variable like ?int userId = HttpContext.Session.GetINT32("ID") to use this variable in that method.

如何以一种可以在其他Action方法中使用它而不使用 HttpContext.Session.GetInt32 语句的方式来全局声明它.我只是尝试使用DRY原理,以使我的代码更简洁.

How can I declare it globally in a way where I can use it in other Action methods without using the HttpContext.Session.GetInt32 statement. I am just trying to use the DRY principle, so that my code is cleaner.

有什么帮助吗?

推荐答案

public class HomeController : Controller
{
    private readonly DataContext _context;
    private readonly IRepository _repo;

    public HomeController(DataContext context, IRepository repo)
    {
        this._context = context;
        this._repo = repo;
    }

    public int GetUserId()
    {
       return (int)HttpContext.Session.GetInt32("ID");
    }

这篇关于ASP.NET核心会话状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆