我想知道如何设置一个单一的全局变量,以便 ASP.net 网站的所有网页中的命令可以轻松访问它。
这会通过一个类来完成吗?我将如何调用它?
持有唯一用户 ID 但能够在所有网页上使用该 ID 进行 SQL 查询的示例。
最佳答案
明显的地方是Session
。
例如
Session["MyId"] = 99; // to set it
和
myId = Session["MyId"]; // to get it
虽然有时 Sessions 会崩溃。所以另一个地方是 Cookie - 假设它不是敏感数据......
// Setting a cookie
HttpCookie myCookie = new HttpCookie("MyID");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
您可以通过以下方式读取 cookie:
HttpCookie myCookie = Request.Cookies["MyId"];
myId = myCookie.Value;
关于c# - 单个全局变量 asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13730693/