'Execute R Script from C# for Core .NET GET API

We are trying to execute an R script from C# for .NET core GET API in visual studio and are not able to return any status from R script (as execution status). Below is what we have tried. Versions - .NET Core 3.1, R 4.2

C# Code:

[HttpGet]
public IActionResult RunRScript()
{
    try
    {
        var rpath = @"C:\Users\AppData\Local\Programs\R\R-4.2.0\bin\Rscript.exe";
        string FilePath = Directory.GetCurrentDirectory() 
            + "\\RScripts\\Sample.R";
        var output = RFromCmd(rpath, FilePath, "");
        return Ok(output);
    }
    catch (Exception e)
    {
        return BadRequest(e.Message.ToString());
    }
}
public static string RFromCmd(string rScriptExecutablePath,
     string rCodeFilePath, string args)
{
    string result = string.Empty;
    try
    {
        var info = new ProcessStartInfo();
        info.FileName = rScriptExecutablePath;
        info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
        info.Arguments = rCodeFilePath;



        info.RedirectStandardInput = false;
        info.RedirectStandardOutput = true;
        info.UseShellExecute = false;
        info.CreateNoWindow = true;



        using (var proc = new Process())
        {
            proc.StartInfo = info;
            proc.Start();
        }
    }
}

Sample.R

getwd()
#Dummy data
sample <- data.frame(Date = seq(as.Date("2000/1/1"), by = "month",
length.out = 200), Volume = rnorm(200))

summary(sample)
#To save the Data in csv format
write.csv(sample, "Sample_data.csv")
View(summary(sample))

#Trying to include return statement
end_of_script <- function() {
  x = 1 #also tried string "complete"
  return(x)
}
end_of_script()

Please let me know what we are missing or doing wrong. The R script is a test script, based on the success of this we will be running different R Scripts using this method.



Solution 1:[1]

Instead of running it like this you can build the restapi with one endpoint using R ,and can call the endpoint in c#

Reference for building APIs in r . https://www.google.com/amp/s/www.geeksforgeeks.org/building-rest-api-using-r-programming/amp/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 saicharan kr