【问题标题】:WebAPI controller that handle json to write file处理 json 以写入文件的 WebAPI 控制器
【发布时间】:2019-08-17 10:22:48
【问题描述】:

我需要用 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 时希望没有创建的文件。 请注意他的 cmets,因为这个带有 StreamWriter 对象的解决方案不起作用。 如何解决这个问题? 有没有其他方法可以在服务器上的txt文件中写入一些文本?

【问题讨论】:

    标签: c# asp.net visual-studio asp.net-web-api asp.net-core


    【解决方案1】:

    如果您使用的是 ASP.NET 核心,那么我建议您执行以下操作。

    创建一个 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 服务返回 IActionResultHttpPost 应该在成功时返回 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 NotFound500 ServerError

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

    【讨论】:

    • 非常感谢您的帮助,您很好地描述了我的问题的解决方案
    【解决方案2】:

    您可以使用此代码来创建您的文件

     using(StreamWriter sw = File.AppendText("your path"))
     {
    
          sw.WriteLine("your text");                     
    
      }     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2012-09-10
      • 2013-02-15
      • 1970-01-01
      相关资源
      最近更新 更多