简体   繁体   English

C#会话变量/应用程序范围的变量

[英]C# Session Variables/Application-wide Variables

I'm new to C# from ColdFusion and I'm trying to replicate an application I have developed in CF to help me get an understanding of the language. 我是ColdFusion C#新手,我正在尝试复制我在CF中开发的应用程序,以帮助我理解该语言。

My application logs a user in and searches and buys virtual items. 我的应用程序登录用户并搜索和购买虚拟物品。

In my CF app, when a user logs in I set a session variable called loggedIn which is true . 在我的CF应用程序中,当用户登录时,我设置了一个名为loggedIn的会话变量,该变量为true

Each search/buy request can only be made whilst this session variable is true . 每个search/buy请求只能在此会话变量为true发出。 If a request returns a expired session response from the host then I update session.loggedIn = false . 如果请求从主机返回了过期的会话响应,那么我将更新session.loggedIn = false A new login request is then made. 然后发出新的登录请求。

How would I achieve this in C# so that I don't need to pass it to and return it from each class/method that it interacts with? 我将如何在C#中实现此目标,从而无需将其传递给与之交互的每个类/方法并从中返回它?

Basically, in CF I can set and access it from anywhere within the application but is this achievable in C#? 基本上,在CF中,我可以从应用程序中的任何位置进行设置和访问,但这在C#中可以实现吗?

Your logged session could be a class that you instantiate when the user logs in, an that you invalidate/destroy when it expires. 记录的会话可以是用户登录时实例化的类,也可以是过期时使之无效/销毁的类。

Then you shoul move the relevant methods inside that class, so they can always be executed because they only exist within the scope of the active session. 然后,您应该该类移动相关方法,因此它们始终可以执行,因为它们仅存在于活动会话的范围内。

If you simply want to set a session value, then you can use the Session property, which is available to a WebForm, or Controller (it's not clear if you're using WebForms or MVC). 如果您只是想设置会话值,则可以使用Session属性,该属性可用于WebForm或Controller(尚不清楚是使用WebForms还是MVC)。

Either way, using that proeprty is the same for both eg 无论哪种方式,使用属性都是相同的,例如

Writing 写作

Session["loggedIn"] = true;

Reading

bool isLoggedIn = Convert.ToBoolean(Session["loggedIn"]);

I suggest you create a property on your WebForm/Controlle to wrap this functionality eg 我建议您在WebForm / Controlle上创建一个属性以包装此功能,例如

public bool UserIsLoggedIn
{
    get
    {
        if (Session["loggedIn"] != null)
        {
            return Convert.ToBoolean(Session["loggedIn"]);
        }

        return false;
    }
    set
    {
        Session["loggedIn"] = value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM