使用Nancy 为Winform中增加web server功能

发布时间 2023-09-14 21:45:00作者: harrychinese

组件

  • Nancy.Hosting.Self.dll
  • Nancy.dll
  • Newtonsoft.Json.dll

Nancy 的两个库应该选用v1的最后版本号, 不要使用v2版, v2版架构有较大变化但文档又不完善, 而且已经停止开发. Nancy.Hosting.Self 库可以帮助我们在console或winforms程序中增加web server功能, 而不用专门部署到IIS等服务器中.

源码


using Nancy;
using Nancy.Extensions;
using Nancy.Hosting.Self;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private NancyHost host;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Nancy Self Host 必须加上 AutomaticUrlReservationCreation, 否则 host.Start()会报异常
            HostConfiguration hostConfigs = new HostConfiguration()
            {
                UrlReservations = new UrlReservations() { CreateAutomatically = true }
            };

            // 创建 NancyHost 实例
            host = new NancyHost(new Uri("http://localhost:18080"), new DefaultNancyBootstrapper(), hostConfigs);

            // 启动 NancyHost
            host.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 停止 NancyHost
            host.Stop();
        }
    }

    /// <summary>
    /// 使用NancyModule来定义路由
    /// </summary>
    public class CustomNancyModule : NancyModule
    {
        public CustomNancyModule()
        {
            // 路由 /hello
            Get["/hello"] = parameters => "Hello, World!";

            //路由 pattern
            Get["/product/{category}"] = parameters => "My category is " + parameters.category;

            //路由 pattern, 限制类型为int
            Get["/favoriteNumber/{value:int}"] = parameters =>
            {
                return "So your favorite number is " + parameters.value + "?";
            };

            // 路由 /data , POST json
            Post["/data"] = parameters =>
            {
                // 获取 POST 的 JSON 字符串
                var jsonData2 = this.Request.Body.AsString();

                //使用 Newtonsoft 将 json字符串转成 JObject 对象
                JObject jobject = (JObject)JsonConvert.DeserializeObject(jsonData2);

                // 返回一个响应,可以根据需要进行处理
                return Response.AsJson(new { Message = "JSON received successfully" });
            };

            // would capture routes like /products/1034 sent as a DELETE request
            Delete[@"/products/(?<id>[\d]{1,7})"] = parameters =>
            {
                return 200;
            };
        }
    }
}

测试代码

GET http://localhost:18080/hello HTTP/1.1
content-type: application/json
 

 
GET http://localhost:18080/product/popular HTTP/1.1
content-type: application/json
 


POST http://localhost:18080/data HTTP/1.1
content-type: application/json

{
    "name": "sample",
    "time": "Wed, 21 Oct 2015 18:27:50 GMT"
}