是否可以在 Application_Start() 中找出正在使用的主机?
不,不是。
根据您的 cmets,我想说您所追求的持久性机制是服务器端缓存选项之一(System.Runtime.Caching 或 System.Web.Caching)。
System.Runtime.Caching 是这两种技术中较新的一种,它提供了一个抽象的ObjectCache 类型,可以潜在地扩展为基于文件的类型。或者,有一个内置的MemoryCache 类型。
与使用静态方法不同,缓存将根据超时(固定或滚动)为所有用户(和所有域)保持状态,并且可能具有缓存依赖性,这将导致缓存立即失效。一般的想法是在缓存过期后从存储(文件或数据库)重新加载数据。缓存保护存储免受每个请求的命中 - 仅在达到超时或缓存失效后才命中存储。
您可以在第一次访问缓存时填充缓存(大概是在请求已经填充之后,而不是在Application_Start 事件中),并使用域名作为缓存键的一部分(或全部)用于查找数据。
public DataType GetData(string domainName)
{
// Use the domain name as the key (or part of the key)
var key = domainName;
// Retrieve the data from the cache (System.Web.Caching shown)
DataType data = HttpContext.Current.Cache[key];
if (data == null)
{
// If the cached item is missing, retrieve it from the source
data = GetDataFromDataSource();
// Populate the cache, so the next request will use cached data
// Note that the 3rd parameter can be used to specify a
// dependency on a file or database table so if it is updated,
// the cache is invalidated
HttpContext.Current.Cache.Insert(
key,
data,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(10),
System.Web.Caching.CacheItemPriority.NotRemovable);
}
return data;
}
// Usage
var data = GetData(HttpContext.Current.Request.Url.DnsSafeHost);
如果它很重要,您可以使用类似于Micro Caching in ASP.NET 的锁定策略(或只使用该解决方案批发),以便在缓存过期时数据源不会收到多个请求。
此外,您可以指定项目为“不可移除”,这将使它们在应用程序池重新启动时仍然存在。
更多信息:http://bartwullems.blogspot.com/2011/02/caching-in-net-4.html