You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于ASP.NET托管的NancyFX简易API:JSON文件读写接口实现问题

刚好我之前用NancyFX在ASP.NET里做过类似的API,给你整理了完整的实现方案,直接套用就行:

1. 先安装必要的NuGet包

首先得把Nancy和JSON序列化的包装上,打开NuGet包管理器控制台,运行这两个命令:

Install-Package Nancy
Install-Package Newtonsoft.Json
2. 实现Nancy API模块

创建一个继承自NancyModule的类,把Get和Set的逻辑都写在这里,重点是不要硬编码文件路径,用相对路径更灵活:

using Nancy;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;

public class ApiModule : NancyModule
{
    private readonly string _dataFilePath;

    public ApiModule()
    {
        // 获取与应用根目录同级的data.json路径(部署后也能正常工作)
        _dataFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data.json");

        // 处理GET请求:返回data.json的内容
        Get["/api/get"] = _ =>
        {
            try
            {
                if (!File.Exists(_dataFilePath))
                {
                    // 文件不存在时返回404和提示信息
                    return Response.AsJson(new { message = "Data file not found" }, HttpStatusCode.NotFound);
                }

                var fileContent = File.ReadAllText(_dataFilePath);
                var jsonData = JsonConvert.DeserializeObject(fileContent);
                return Response.AsJson(jsonData);
            }
            catch (Exception ex)
            {
                // 捕获异常,返回服务器错误
                return Response.AsJson(new { error = ex.Message }, HttpStatusCode.InternalServerError);
            }
        };

        // 处理POST请求:修改data.json的内容
        Post["/api/set"] = async _ =>
        {
            try
            {
                // 读取请求体里的JSON数据
                var requestBody = await Request.Body.ReadAsStringAsync();
                if (string.IsNullOrWhiteSpace(requestBody))
                {
                    return Response.AsJson(new { error = "Request body cannot be empty" }, HttpStatusCode.BadRequest);
                }

                // 先验证JSON格式是否合法,避免写入无效数据
                try
                {
                    JsonConvert.DeserializeObject(requestBody);
                }
                catch (JsonException jsonEx)
                {
                    return Response.AsJson(new { error = $"Invalid JSON: {jsonEx.Message}" }, HttpStatusCode.BadRequest);
                }

                // 写入文件覆盖原有内容
                File.WriteAllText(_dataFilePath, requestBody);
                return Response.AsJson(new { message = "Data updated successfully" });
            }
            catch (UnauthorizedAccessException)
            {
                return Response.AsJson(new { error = "No permission to write to data file" }, HttpStatusCode.Forbidden);
            }
            catch (Exception ex)
            {
                return Response.AsJson(new { error = ex.Message }, HttpStatusCode.InternalServerError);
            }
        };
    }
}
3. 配置ASP.NET托管Nancy

在你的Global.asax.cs里注册Nancy的引导程序,让ASP.NET能处理Nancy的请求:

using Nancy;
using Nancy.Hosting.Aspnet;
using System;

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        // 注册默认的Nancy引导程序
        NancyBootstrapper.Bootstrapper = new DefaultNancyBootstrapper();
    }
}
几个关键注意事项
  • 文件路径设置:把data.json放在项目根目录,然后在文件属性里设置「复制到输出目录」为「如果较新则复制」,这样部署的时候文件会跟着走。
  • 权限问题:确保你的ASP.NET应用程序池身份对data.json所在的目录有读写权限,不然会出现访问被拒绝的错误。
  • 错误处理:代码里加了异常捕获,返回对应的HTTP状态码和错误信息,方便你调试和前端处理。

内容的提问来源于stack exchange,提问作者prou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:16:38