我希望能够从与 ASP.NET 网站在同一服务器上运行的控制台应用程序中清除特定的缓存项。
如果我引用 System.Web,然后尝试 System.Web.HttpContext.Current,我总是得到 null,这是有道理的。
我尝试使用此代码,System.Web.HttpContext.Current 变为非空。
代码:
HttpContext.Current = new HttpContext(
new HttpRequest("", "http://tempuri.org", ""),
new HttpResponse(new StringWriter())
);
// User is logged in
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity("username"),
new string[0]
);
// User is logged out
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity(String.Empty),
new string[0]
);
但是HttpContext.Current.Application无法使用。我尝试这样做:
..
HttpContext.Current.Application.Add("TestValue", 1);
..
object objReturn = HttpContext.Current.Application.Get("TestValue");
if(objReturn==null)
Console.WriteLine("objReturn is null");
else
Console.WriteLine(objReturn);
我的问题是变量objReturn
始终为空。
其他人对于如何实现这一目标有更好的想法吗?
最佳答案
缓存位于 ASP.NET 工作进程内部,您无法直接从控制台应用程序访问它。 HttpContext.Current 为 null,因为您不在 Web 上下文中。
我会向应用程序本身添加一个网页,允许您清除缓存项目。
关于c# - 从单独的控制台应用程序访问 HttpContext.Current.Application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11644687/