不知道你为什么需要那个。您可以将会话独有的内容存储在 HTTPContext.Current.Session 中。您可以在 HTTPContext.Current.ViewState 中存储对请求唯一的内容。
要执行您想做的事情,您需要声明一个线程安全对象的应用程序范围变量。下面的示例将为您提供一个跨所有页面的唯一编号。
1) 创建一个线程安全的计数器类,因为应用程序范围的变量默认不是线程安全的
public class ThreadSafeCounter
{
private object _padlock = new object;
private int _counterValue = 0;
public int GetNextValue()
{
int temp;
lock(_padlock)
{
_counter++;
temp = _counter;
}
return temp;
}
}
2) 在 Global.asax Application_Start 事件中创建应用程序变量
HttpContext.Current.Application["MyCounter"] = new ThreadSafeCounter();
3)在您的页面代码中访问它
var counter = HttpContext.Current.Application["MyCounter"] as ThreadSafeCounter;
if (counter != null)
{
var uniqueValue = counter.GetNextValue();
// DO SOME WORK HERE
}
else
{
//throw some exception here
}
一个潜在的陷阱:
如果你在服务器场中部署它或者你有超过 1 个工作进程,请确保你的会话模式是基于状态服务器或 SQL Server,因为如果它是 InProc,则处理请求的每个服务器/进程会有自己的柜台。