【发布时间】: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