开始服务思想 ASP.net 页

Start a Service thought ASP.net Page

我写了一个 windows 服务,效果很好。它是通过 ChatServer.exe {argument} 调用(在命令提示符下),其中 {argument} 是关键工作,例如 installuninstallstartstop .

此服务所在的程序需要管理权限(因为它 install/uninstall 本身)。因此,例如,如果我以管理员 "D:\folder\chatserver.exe install" 身份启动 cmd,它会按应有的方式安装服务。

嗯,我的问题是,在我的 ASP.net 站点上,我写了一个函数(如下)来启动该过程,但是我得到一个异常 "740" ("the software required privilege elevation"),就好像我标记了 "AsAdmin" 我的函数参数为 "true",我知道 "UseShellExecute" 不能作为例外为真。

public static int RunProcess(string ApplicationPath, string Parameters = "", bool AsAdmin = false)
{
    try
    {
        global::System.Diagnostics.ProcessStartInfo startInfo = new global::System.Diagnostics.ProcessStartInfo();
        startInfo.UseShellExecute = AsAdmin;
        if (AsAdmin) { startInfo.Verb = "runas"; }
        startInfo.WorkingDirectory = global::System.IO.Path.GetDirectoryName(ApplicationPath);
        startInfo.FileName = ApplicationPath;
        if (!string.IsNullOrEmpty(Parameters)) { startInfo.Arguments = Parameters; }
        startInfo.ErrorDialog = false;
        global::System.Diagnostics.Process process = global::System.Diagnostics.Process.Start(startInfo);
        process.WaitForExit();
        return process.ExitCode;
    }
    catch (global::System.ComponentModel.Win32Exception ex) { return ex.NativeErrorCode; }
    catch { return -1; }
}

我该怎么办?

你试过ProcessStartInfo了吗?它允许您添加特定的 credentials。检查下面的例子:

ProcessStartInfo myProcess = new ProcessStartInfo(path);
myProcess.UserName = username;
myProcess.Password = MakeSecureString(password);
myProcess.WorkingDirectory = @"C:\Windows\System32";
myProcess.UseShellExecute = false;
// elevate EDIT
myProcess.Verb = "runas";
Process.Start(myProcess);


private static SecureString MakeSecureString(string text)
{
     SecureString secure = new SecureString();
     foreach (char c in text)
     {
         secure.AppendChar(c);
     }
     return secure;
}

Launch a process under another user's credentials

除了 Ted 的回答,我还要补充一下:

Microsoft 不建议从 Web application/site 调用 .exe,因为 w3wp.exe 出于安全原因在沙盒环境中运行,因此它启动的任何 thread/task/process 都不相同就像您自己启动它时一样,因此可能无法按预期工作。

您可能希望将控制台应用程序重新编码为 ASP.NET Web API,可能托管在 IIS 或 Windows 服务中。

你不能也不应该这样做。您不希望将管理凭据存储在您的 Web 应用程序附近的任何位置,并且您绝对不希望 运行 您的 Web 应用程序处于管理权限下。

一个解决方案是实际拥有一个 "watchdog" Windows 服务,运行 适当的权限与服务控制管理器 (SCM) 交互,它通过例如 WCF 接受命令在本地主机上,让您的 Web 应用程序与该服务对话,该服务又会启动或停止相应的服务。

看起来像这样:

[Web Application] -- WCF --> [Watchdog Service] -- SCM --> [Chat Service]

因此您的 Web 应用程序通过 WCF 发送 StartService("ChatService") 命令,然后 Watchdog 服务启动 ChatService 服务。

现在只有 Watchdog 服务必须 运行 在管理权限下,并保护 WCF 通信以确保只有经过身份验证的应用程序调用它,这在其他问题中讨论。

如果您正在尝试开发一个包括网站和服务的自安装网络平台,请考虑使用合适的安装程序,而不是全部手动安装。