我需要用 asp.net 编写一个 restfull 的 api,它在主体中接收一个 json,例如:
"{
\"name\" : \"name of the file\",
\"path\" : \"path of the file\",
\"body\" : \"body of th file\"
}"
并用这个 json 中的数据在服务器中写入一个文件。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace tool_put.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpPost]
public String Post([FromBody] string value)
{
dynamic obj = JsonConvert.DeserializeObject(value);
String path = obj.path + obj.name + ".txt";
//StreamWriter Data = new StreamWriter(MapPath("~/"+path), (System.Text.Encoding)true);
// Data.WriteLine(obj.body);
return "true";
}
}
}
我在 mac 上使用了 visual studio,当我在本地主机上运行它并尝试从 postman 执行 http post 时,希望没有创建的文件。 请注意,他发表评论是因为使用 StreamWriter 对象的此解决方案不起作用。 如何解决这个问题? 有没有其他方法可以在服务器上的 txt 文件中写入一些文本?
请您参考如下方法:
如果您使用的是 ASP.NET Core,那么我建议您执行以下操作。
创建一个 DTO(数据传输对象)并让框架 model binding为您处理序列化/反序列化。
public class FileDto
{
public string Name { get; set; }
public string Path { get; set; }
public string Body { get; set; }
}
Asp.Net Core 没有等同于 Server.MapPath 的东西。要获取 Web 根路径,您可以实现 IWebHostEnvironment,详见 here .
但是,下面的示例仅使用硬编码值。我建议为您的 RESTful 服务返回 IActionResult。 HttpPost 应该在成功时返回 Created 201 响应。下面的代码将在响应正文中返回 201 Created 状态和文件 DTO。
[HttpPost]
public IActionResult Post([FromBody] FileDto model)
{
string directory = System.IO.Path.Combine(@"C:\temp\myfiles", model.Path);
// TODO verify directory exists, Name is not null, Path is not null, Body is not null
string fileName = model.Name + ".txt";
string fullPath = System.IO.Path.Combine(directory, fileName);
// simplest way to write to file
System.IO.File.WriteAllText(fullPath, model.Body);
return Created("http://url/to/your/new/file", model);
}
如果您想将文本附加到现有文件,则可以使用 File.AppendAllText(path, text) .
API 接收到的路径可能不存在,您需要处理不存在的情况并决定如何处理。例如,您可以创建目录,或返回 404 NotFound 或 500 ServerError。
如果您不知道数据来自何处,允许 API 客户端/用户选择/创建文件路径可能不是一个好主意(如果用户/客户端发送了 "path": ". ./.." 例如路径)。
