【发布时间】:2021-08-10 22:31:46
【问题描述】:
在 .net Core API 中,我有一个带有 HttpPost 端点的数据控制器,该端点从另一个 Web 应用程序接收 json 字符串。 这个 json 字符串可以包含 1 到 5 条记录,由一个 Id、一个描述和一个 base64 图像的字符串组成。 我需要创建一个名为 Data.xml 的 XML 文件,如果它不存在并使用 json 字符串值填充它。 我见过这样的例子:
XDocument document = new XDocument();
if(!File.Exists("MyXmlFile.xml")){
//Populate with data here if necessary, then save to make sure it exists
document.Save("MyXmlFile.xml");
}
else{
//We know it exists so we can load it
document.load("MyXmlFile.xml");
}
File红色高亮,using语句找不到File命名空间System.IO.File 我还安装了 System.IO.FileSystem NuGet 包,也没有运气。 我曾尝试在 NET Core 3.1 中也有的单独 API 中执行相同操作,但我也无法执行此操作。 有谁知道可能出了什么问题?
控制器代码:
using aspnetcore_api_server.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Xml.Linq;
using System.IO.File;
namespace aspnetcore_api_server.Controllers
{
[ApiController]
[Route("[controller]")]
public class DataController : ControllerBase
{
[HttpGet]
public IEnumerable<DataModel> Get()
{
return null;
}
[HttpPost]
public List<DataModel> Post([FromBody] string records)
{
XDocument dataDocumentStorage = XDocument.Load("Data.xml");
XDocument document = new XDocument();
if (!File.Exists("Data.xml"))
{
//Populate with data here if necessary, then save to make sure it exists
document.Save("Data.xml");
}
else
{
//We know it exists so we can load it
//document.("Data.xml");
}
return null;
}
}
}
【问题讨论】:
-
System.IO.File - 您需要 System.IO 的 using 语句或完全限定它
-
如果我完全设置“使用 System.IO.File”,则找不到文件,在 System.IO 不显示文件作为选项后键入点
-
我不知道你为什么会遇到这个问题,但我保证这是 .NET Core 中的问题。也许 Visual Studio 提示您生成一个类并且您接受了它,现在您已经定义了自己的 System.IO 命名空间。在您的代码中搜索定义它的文件并将其删除。
-
会不会是因为它是 API 而不是 Web 应用?我很迷茫,我尝试在另一个我拥有的 api 中做同样的事情并得到相同的结果......文件没有显示出来......我什至安装了包 System.IO.Filesystem 也没有香蕉......跨度>
-
我已投票决定重新开放。 OP删除了错字,这个问题有一个非常真实,正确的答案。
标签: c# xml api asp.net-core