如何在 C# 中使用 HTTP Post 方法执行 cmds

时间:2021-01-18 20:15:47

标签: c# powershell api rest cypress

我们在服务器上安装了一个 REST 端点作为 Windows 服务。该服务器将用于测试自动化。这个想法是向端点发出 POST 请求,该端点将根据 POST url 中指定的参数启动 cypress 测试。

我有一个现有的 powershell 脚本可以执行此操作。理想情况下,我想调用该脚本并填写所需的参数。

无论我做什么,请求都会返回 OK 而不实际运行任何命令。有没有办法使用 POST 请求来执行 cmds 或 powershell 脚本?下面的代码(注意:我在这里尝试两种不同的方法都不起作用):

namespace CNet.TestRunner
{
    public class AddTestRun : CNetApiEndpoint
    {
        [HttpPost("Cypress/{testName}/{serverName}")]
        public CineNetResult TestRun(string testName, string serverName)
        {
            string test = testName + ".js";

            string testPath = $@"..\EndToEndSpecs\cypress\integration\{test}";

            var path = "%PROGRAMFILES%";
            var resolvedPath = Environment.ExpandEnvironmentVariables(path);
            string cmd = $@"{resolvedPath}\PowerShell\7\pwsh.exe "" '..\EndToEnd.ps1' '-TestPath {testPath}' '-HostToTest {serverName}' """;


            Process P = Process.Start($@"{resolvedPath}\PowerShell\7\pwsh.exe", $@""" '..\EndToEnd.ps1' '-TestPath {testPath}' '-HostToTest {serverName}'""");
            P.WaitForExit();
            int result = P.ExitCode;
            string resStr = result.ToString();
            
            var model = new ResponseModel
            {
                Message = resStr,
                DataPassed = $"{testName}|{serverName}"
            };
            var proc1 = new ProcessStartInfo();
            string anyCommand = "yarn install";
            proc1.UseShellExecute = true;

            proc1.WorkingDirectory = @"C:\Windows\System32";

            proc1.FileName = @"C:\Windows\System32\cmd.exe";
            proc1.Verb = "runas";
            proc1.Arguments = "/c " + anyCommand;
            proc1.WindowStyle = ProcessWindowStyle.Hidden;
            Process.Start(proc1);

            return Ok(model);

        }
    }
}

0 个答案:

没有答案