【问题标题】:Storing UserID and Username as global variable将用户 ID 和用户名存储为全局变量
【发布时间】:2014-11-20 01:18:52
【问题描述】:

我对 ASP.NET 非常陌生,因此请在您的回复中考虑到这一点。

我有一个方法可以为我的用户名和用户 ID 创建一个会话 cookie,当我将它放入后面的代码时(见下文)

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.User.Identity.IsAuthenticated) // if the user is already logged in
    {
        MembershipUser currentUser = Membership.GetUser();

        Guid CurrentUserID = (Guid)currentUser.ProviderUserKey;
        string CurrentUsername = (string)currentUser.UserName;

        Session["CurrentUserID"] = CurrentUserID;
        Session["CurrentUserName"] = CurrentUsername;
    }
    else
    {
        Session["CurrentUserID"] = "";
        Session["CurrentUserName"] = "";
    }
}

我正在尝试清理我的项目,并认为将任何方法存储到我的 App_code 目录中的类文件中是明智的,这样我每个方法只有一个实例。

当我收到多个错误时,我不能将上面的代码剪切并粘贴到类文件(下面)中。

我想知道将这些存储为全局变量的最佳做法是什么?

我的 App_code 文件夹中的类文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

/// <summary>
/// Generic utilities that can be accessed from any page
/// </summary>
public static class GlobalUtilities
{


    //Takes x characters from the right hand side. TO USE: MyString.TxtStrRight(8)
    public static string TxtStrRight(this string value, int length)
    {
        if (String.IsNullOrEmpty(value)) return string.Empty;

        return value.Length <= length ? value : value.Substring(value.Length - length);
    }

    //Takes x characters from the left hand side. TO USE: MyString.TxtStrLeft(40)
    public static string TxtStrLeft(this string value, int length)
    {
        if (String.IsNullOrEmpty(value)) return string.Empty;

        return value.Length <= length ? value : value.Substring(0, length) + "...";
    }

    //Get the difference between time and date of NOW and the database value. TO USE: GlobalUtilities.GetDiffDate(MyDate)
    public static string GetDiffDate(DateTime dt)
    {
        TimeSpan ts = dt - DateTime.Now;
        if (Math.Abs(ts.TotalHours) < 24 && Math.Abs(ts.TotalHours) >= 1)
        {
            return string.Format("{0:0} hrs ago", Math.Abs(ts.TotalHours));
        }
        else if (Math.Abs(ts.TotalHours) < 1)
        {
            return string.Format("{0:0} mins ago", Math.Abs(ts.TotalMinutes));
        }
        else
        {
            return dt.ToString("dd MMM yyyy");
        }
    }



}

【问题讨论】:

    标签: c# asp.net global-variables userid


    【解决方案1】:

    Page_Load 是一个事件处理程序,用于处理在 ASP .Net Web 请求的生命周期中发生的 page.load 事件。虽然它实际上是一种方法,但它不是您在 GlobalUtilities 类中的扩展方法的意义上的方法。如果您尝试将该方法从触发 Page.Load 事件的上下文中取出,它将不起作用。

    如果您的目标是抽象设置会话变量的代码,以避免重复,您可以创建不同的方法来显式处理。

    它可能看起来像这样:

    public static void SetSessionVariables(this MembershipUser currentUser) {
        Guid CurrentUserID = (Guid)currentUser.ProviderUserKey;
        string CurrentUsername = (string)currentUser.UserName;
    
        Session["CurrentUserID"] = CurrentUserID;
        Session["CurrentUserName"] = CurrentUsername;
    }
    

    然后您的 Page_Load 处理程序将如下所示:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.User.Identity.IsAuthenticated) { // if the user is already logged in
            MembershipUser currentUser = Membership.GetUser();
    
            currentUser.SetSessionVariables();
        }
        else
        {
            Session["CurrentUserID"] = "";
            Session["CurrentUserName"] = "";
        }
    }
    

    仍然会留下一些东西。如果出于无法移动事件处理程序本身的相同原因,则无法将初始值移出事件处理程序;在此上下文之外,您将无法使用 Page 对象。

    就存储全局数据的最佳方式而言,Session 是一个不错的选择。唯一的缺点是 Session 本身是 HttpContext 的一个属性;因此,除非您在方法之间传递上下文,否则它将无法在您的表示层(Web 项目)之外使用,这很糟糕。

    【讨论】:

    • 这是一个很好的解释。谢谢。我试了一下,但收到错误消息:名称“会话”在我的类文件的当前上下文中不可用。
    • Session 是 HttpContext 的一个属性,所以你可以尝试通过 HttpContext.Current.Session 来访问它,但是你可能只是 SOL,取决于 App_Code 文件夹的工作方式,HttpContext 可能不可用。但是,您可以通过将全局 utils 类移动到 Web 项目的根目录(因此它不在其自己的命名空间中)来获得相同的结果(使方法全局可访问)。如果它在根命名空间中,所有后代都将自动访问它,并且由于它是一个静态类,您不需要实例化它,并且永远只有一个。
    • 您能否解释一下如何将全局 utils 移动到根命名空间中?
    • 您可以将整个文件(我猜是 GlobalUtilities.cs)从 App_Code 文件夹中移出,并移到 Web 项目的根文件夹中(Web.Config 文件所在的位置)。这会将其放入项目的根目录中。我认为这应该是您需要做的所有事情,但是如果您想手动指定命名空间,它将是您的类块之外的一个新块,如下所示:namespace ProjectName{public static class GlobalUtilities{@987654327 @}}
    • 感谢您花时间解释。我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多