我需要创建一个名为 publish 的方法,以 JSON 格式获取名称、描述、端点、操作数和操作数类型,并将其写入文本文件。我已经实现了那部分,但是在第一次 API 调用之后,文本文件中的文本被覆盖,这不是我想要的。我在下面包含了模型类和控制器类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Registry.Models
{
public class publishModel
{
public string Name { get; set; }
public string Description { get; set; }
public string endpoint { get; set; }
public int NoOfoperands { get; set; }
public string operandType { get; set; }
}
}
using Newtonsoft.Json;
using Registry.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Web.Http;
namespace Registry.Controllers
{
public class publishController : ApiController
{
[Route("api/publish")]
[HttpPost]
public string publish(publishModel pModel)
{
string servicePath = @"C:\Users\ASUS\source\repos\DC assignment 1\Services.txt";
MemoryStream ms = new MemoryStream();
var write = new Utf8JsonWriter(ms);
write.WriteStartObject();
write.WriteString("Name", pModel.Name);
write.WriteString("Description", pModel.Description);
write.WriteString("Endpoint", pModel.endpoint);
write.WriteString("No of operands", pModel.NoOfoperands.ToString());
write.WriteString("Operand type", pModel.operandType);
write.WriteEndObject();
write.Flush();
string json = Encoding.UTF8.GetString(ms.ToArray());
//string json = JsonConvert.SerializeObject(pModel);
try
{
using (StreamWriter writer = new StreamWriter(servicePath))
{
writer.Write(json);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return "Description saved";
}
}
}