我有下一个问题。我想做一些" crud"使用web api(.net core)对ubuntu中的某些文件(存储在vm中)进行操作。问题是当我对服务器进行POST调用时,我得到了500.我使用像web服务器这样的apache。如果我再打一次电话(GET电话),一切都很完美。
[Route("api/[controller]")]
public class CompilationController : Controller
{
private ICompilationFile _compilationFile;
public CompilationController(ICompilationFile compilationFile)
{
_compilationFile = compilationFile;
}
// GET: api/<controller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "compile", "compile" };
}
// POST api/<controller>
[HttpPost]
public string Post([FromBody]CompilationModel item)
{
if (ModelState.IsValid)
{
var response = _compilationFile.CompileFile(item.Content, item.Language, item.ProblemName, item.Username);
return JsonConvert.SerializeObject(new ResponseModel {
CompilationResponse = response.Item1.ToString(),
OutputMessage = response.Item2 });
}
return "Failed response";
}
对于GET,请致电。
这是与文件一起使用的代码部分:
public void GenerateFile(string content, string language, string
problemName, string userName)
{
//create directory
var goodDirectory = GetCurrentDirectory();
if (!Directory.Exists(goodDirectory))
{
Directory.CreateDirectory(goodDirectory);
}
StringBuilder sb = new StringBuilder();
string problemFullName = Builder.BuildProblemName(problemName, userName);
sb.Append(problemFullName).Append(LanguageHelper.GetLanguageExtenstionType(language));
string sourceName = sb.ToString();
//create file
var fileToCreate = Path.Combine(goodDirectory, sourceName);
if(File.Exists(fileToCreate))
{
File.Delete(fileToCreate);
}
if (!File.Exists(fileToCreate))
{
using (FileStream fs = new FileStream(fileToCreate, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
content = content.Trim();
StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
writer.WriteLine(content);
writer.Flush();
}
}
}
public Tuple<Verdict, string> GetVerdictForFile(string argument,string workingDirectory)
{
Process process = new Process();
process.StartInfo.FileName = "/bin/bash";
process.StartInfo.Arguments = $"-c \"{argument}\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WorkingDirectory = workingDirectory;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
process.Close();
Verdict verdict = Verdict.SUCCESS;
if(!string.IsNullOrEmpty(err))
{
verdict = Verdict.ERROR;
}
StringBuilder sb = new StringBuilder("Output: ").Append(output);
if(verdict == Verdict.ERROR)
{
sb.AppendLine().Append("CompilationErrors: ").Append(err);
}
return new Tuple<Verdict, string>(verdict, sb.ToString());
}
如果我直接在ubuntu中为#34; crud&#34;写一个不同的项目(一个控制台项目)。对文件的操作一切正常。