试图在访问事件日志时执行未经授权的操作错误
本文关键字:授权 错误 操作 执行 访问 事件 日志 | 更新日期: 2023-09-27 17:55:37
我有一个 C# 中的 Windows 服务,它创建一个事件日志,如下所示:
public partial class WizardService : ServiceBase
{
public WizardService()
{
InitializeComponent();
// Setup logging
if (!EventLog.SourceExists("WizardService"))
{
EventLog.CreateEventSource(
"WizardService", "WizardServiceLog");
}
eventLog1.Source = "WizardService";
eventLog1.Log = "WizardServiceLog";
}
Windows 服务可以成功访问此事件日志。 Windows 服务配置为作为本地服务运行。 这需要在Win7和Windows Server 2008 R2上运行。
但是,该服务也会调用 ASMX Web 服务。 我希望 ASMX Web 服务也能够访问相同的事件日志,但出现此错误:
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
at Microsoft.Win32.RegistryKey.Win32ErrorStatic(Int32 errorCode, String str)
at Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(RegistryHive hKey, String machineName, RegistryView view)
at System.Diagnostics.EventLogInternal.GetEventLogRegKey(String machine, Boolean writable)
at System.Diagnostics.EventLogInternal.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
at System.Diagnostics.EventLogInternal.SourceExists(String source, String machineName, Boolean wantToCreate)
at System.Diagnostics.EventLogInternal.VerifyAndCreateSource(String sourceName, String currentMachineName)
at System.Diagnostics.EventLogInternal.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
at System.Diagnostics.EventLog.WriteEntry(String message)
下面是 ASMX Web 服务使用的代码:
public class WizardService : WebService
{
private EventLog eventLog;
public WizardService()
{
eventLog = new EventLog("WizardServiceLog", "localhost", "WizardService");
}
private SomeOtherMethod()
{
eventLog.WriteEntry("Error : " + ex.Message + Environment.NewLine + ex.StackTrace);
}
}
错误发生在 eventLog.WriteEntry() 行上。
这可能是
因为运行 Web 服务的AppPool
没有足够的权限来访问事件日志。
最佳做法是创建一个具有适当访问权限的用户,而不允许所有内容。这样,如果有人入侵您的服务,他们就没有完全权限等。
但是,也就是说,首先将Network Service
或Full Admin Rights
用户分配给AppPool
并检查事件日志是否可访问,然后根据需要调整权限。