【发布时间】:2012-06-08 21:24:03
【问题描述】:
我在我的 ASP.NET Web 应用程序中使用表单身份验证,并在特定表单中使用 FileSystemWatcher。
它有两个事件watcher_Changed 和watcher_Created。事件被正确调用。一旦事件被触发,HttpContext.Current 就会变为 null。
我不知道FileSystemWatcher 是否正在清除会话。谁可以帮我这个事?代码如下。
void watcher_Created(object sender, FileSystemEventArgs e)
{
watcher_Event(sender, e);
}
private void watcher_Event(object sender, FileSystemEventArgs e)
{
try
{
if (getUserName() != null)
{
//Some Code
}
}
}
public string getUserName()
{
FormsIdentity useridentity = (FormsIdentity)HttpContext.Current.User.Identity; //Exception is thrown here. ("Object reference not set to instance of an object")
FormsAuthenticationTicket userticket = useridentity.Ticket;
string username = userticket.Name;
return username;
}
谢谢。
【问题讨论】:
-
您在哪里调用此代码?在某些情况下,您只有一个 HttpContext 用户,但并非在任何地方都有。
-
或者你根本不应该使用 FileSystemWatcher。请考虑其他方法。 HttpContext 是线程本地的,所以你不应该期望它在每个线程中都不为空。
-
@LexLi 您能否建议任何替代方法。非常感谢。
-
您可能会发布有关此表单功能的更多详细信息,以及您决定在一开始就使用 FileSystemWatcher 的原因。然后每个人都可以帮助塑造它。请考虑将其作为一个新的设计问题发布,因为对于这个问题,您已经从@Douglas 那里得到了正确的答案。
-
@LexLi 非常感谢您的回复。表单的功能如下。 1. 用户登录应用程序。 2. 应用程序应继续扫描文件夹以查找添加的任何新文件 (XML)。文件夹的路径是从数据库中读取的。 3. 在文件夹中创建新文件时,应用程序从 XML 文件中读取相关数据并在表单中显示有关该文件的信息。在搜索了实现此功能的相关控件后,我选择了 FileSystemWatcher。我不太确定它在 Web 应用程序中的效果如何。
标签: c# filesystemwatcher