andy andy - 1 month ago 14
ASP.NET (C#) Question

How to Start/Stop a Windows Service from an ASP.NET app - Security issues

Here's my Windows/.NET security stack:


  • A Windows Service running as LocalSystem on a Windows Server 2003 box.

  • A .NET 3.5 Website running on the same box, under "default" production server IIS settings (so probably as NETWORKSERVICE user?)



On my default VS2008 DEV environment I have this one method, which gets called from the ASP.NET app, which works fine:

private static void StopStartReminderService() {

ServiceController svcController = new ServiceController("eTimeSheetReminderService");

if (svcController != null) {
try {
svcController.Stop();
svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
svcController.Start();
} catch (Exception ex) {
General.ErrorHandling.LogError(ex);
}
}
}


When I run this on the production server, I get the following error from the ServiceController:


Source: System.ServiceProcess ->
System.ServiceProcess.ServiceController -> IntPtr
GetServiceHandle(Int32) -> System.InvalidOperationException Message:
Cannot open eTimeSheetReminderService service on computer '.'.


Why is this happening, and how do I fix it?

EDIT:

The answer is below, mostly in comments, but to clarify:


  1. The issue was Security related, and occurred because the NETWORKSERVICE account did not have sufficient rights to Start/Stop a service

  2. I created a Local User Account, and added it to the PowerUsers Group (this group has almost admin rights)

  3. I don't want my whole Web App to impersonate that user all the time, so I impersonate only in the method where I manipulate the service. I do this by using the following resources to help me do it in code:



MS KB article and this, just to get a better understanding

NOTE: I don't impersonate via the web.config, I do it in code. See the MS KB Article above.

Answer

Try adding this to your Web.Config.

<identity impersonate="true"/>
Comments