c# - 处理 json 以写入文件的 WebAPI 控制器
问题描述
我需要用 asp.net 编写一个 api restfull,它在正文中接收一个 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,当我在 localhost 上运行它并尝试从邮递员执行 http post 时希望没有创建的文件。请注意他的评论,因为这个带有 StreamWriter 对象的解决方案不起作用。如何解决这个问题?有没有其他方法可以在服务器上的 txt 文件中写入一些文本?
解决方案
如果您使用的是 ASP.NET 核心,那么我建议您执行以下操作。
创建一个 DTO(数据传输对象)并让框架模型绑定为您处理序列化/反序列化。
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
说明。
但是,下面的示例仅使用硬编码值。我建议您返回IActionResult
RESTful 服务。AnHttpPost
应该在成功时返回 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
or 500 ServerError
。
如果您不知道数据来自哪里,那么允许 API 客户端/用户选择/创建文件路径可能不是一个好主意("path": "../.."
例如,如果用户/客户端发送了路径怎么办)。
推荐阅读
- database - 如何使用循环任务实现数据管道?
- arrays - 无法使用 phpBB 3.3 的请求类获取复选框数组
- ffmpeg - FFMPEG 不能全局化
- intellij-idea - 使用 protobuf 生成的源代码时出现“错误:类型:未找到”
- sql - 未创建数据库,表转到 master
- jwt - jwt 在 woocommerce 中获取产品列表的问题
- elrond - 是否有使 erdJs 与 Angular 12 一起使用的修复/解决方法?
- reactjs - 从 Netlify 上的后端服务器检索数据时出错
- c++ - Why does the C++23 ranges adaptor require a callable object to be copy_constructible?
- r - 以 SDMX 格式循环 URL 并将结果合并到 R 数据帧中