将命令行输出重定向到MVC控制器

时间:2014-12-26 14:22:22

标签: c# visual-studio model-view-controller command-line casperjs

我正在使用Visual Studio 2013使用MVC和C#开发一个互联网应用程序。我需要实现一个能够自动登录网站的功能。为此,我使用CasperJs框架。

以下代码创建一个将在命令行中执行js代码的线程。

[HttpPost]
    public ActionResult Publish()
    {
        try
        {
            new Thread(new ParameterizedThreadStart(x =>
            {
                ExecuteCommand("casperjs test.js");
            })).Start();

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
        catch (Exception e)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);
        }
    }

    private void ExecuteCommand(string Command)
    {
        try
        {
            ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);

            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardOutput = true;

            Process process = Process.Start(processInfo);

            string output = process.StandardOutput.ReadToEnd();

            process.WaitForExit();
        }
        catch (Exception e)
        {
            Trace.Listeners.Add(new TextWriterTraceListener(e.ToString()));
        }
    }

为了确保eveything正确,我想将命令行中产生的输出重定向到我的控制器。我怎么做?使用前面的代码,字符串输出始终为null。

1 个答案:

答案 0 :(得分:0)

我不确定你是否想要实际返回命令的输出作为对Publish的响应,但是改变后的' ExecuteCommand'方法应该有助于从过程中获得标准输出。从那里,您可以根据输出中可能包含的预期值执行您喜欢的操作。

[HttpPost]
public ActionResult Publish()
{
    try
    {
        string cmdResult = "";
        new Thread(new ParameterizedThreadStart(x =>
        {
            cmdResult = ExecuteCommand("casperjs test.js");
        })).Start();

        var response = Request.CreateResponse<string>(System.Net.HttpStatusCode.OK, cmdResult);
        return response;
    }
    catch (Exception e)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);
    }
}

private string ExecuteCommand(string Command)
{
    string result = "";
    try
    {
        ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);

        processInfo.CreateNoWindow = true;
        processInfo.UseShellExecute = false;
        processInfo.RedirectStandardOutput = true;
        processInfo.RedirectStandardError = true;

        Process process = Process.Start(processInfo);
        process.WaitForExit();

        while (!process.StandardOutput.EndOfStream)
        {
            result += process.StandardOutput.ReadLine();
        }

        while (!process.StandardError.EndOfStream)
        {
            result += process.StandardError.ReadLine();
        }
    }
    catch (Exception e)
    {
        Trace.Listeners.Add(new TextWriterTraceListener(e.ToString()));
        throw;
    }

    return result;
}