首页 > 解决方案 > 处理 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 文件中写入一些文本?

标签: c#asp.netvisual-studioasp.net-web-apiasp.net-core

解决方案


如果您使用的是 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说明。

但是,下面的示例仅使用硬编码值。我建议您返回IActionResultRESTful 服务。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 NotFoundor 500 ServerError

如果您不知道数据来自哪里,那么允许 API 客户端/用户选择/创建文件路径可能不是一个好主意("path": "../.."例如,如果用户/客户端发送了路径怎么办)。


推荐阅读