Nancy (二)

3 篇文章 0 订阅
2 篇文章 0 订阅

最近做CS项目,一直在使用TCP+Socket 做数据传输,不太爽,砸门可是多年BS的开发,这样开发接口出去比较费劲,但是又不想用asp.net mvc webapi,要按照IIS,有些工控机的系统环境也是很尴尬的,那么也可以用wcf啊,不用依赖IIS,比较麻烦。所以还是用了Nancy!

1 老规矩,Nuget下载!

2 简单画个页面

 

3 上代码 (NancyModule) 注意Post方法的From参数获取和Body参数获取,代码中均有给到 

/// <summary>
    /// 使用NancyModule来定义路由
    /// </summary>
    public class CustomNancyModule : NancyModule
    {
        //private static readonly XDeclaration _defaultDeclaration = new XDeclaration("1.0", null, null);

        public CustomNancyModule()
        {

            Get("/", x => { return "Hello World!"; });   //  单斜杆位根节点,这里和mvc 中的 路由是一样的

            Get("/greet/{name}", x =>
            {
                return "Hello " + x.name;
            });

            Get("/GetJsonOBJ", x =>
            {
                return Response.AsJson(new { name = "张三" });
            });

            Get("/GetMyText", x =>
            {
                return Response.AsText("我是文本", System.Text.Encoding.UTF8);
            });

            Get("/GetRequsetInfo", x =>
            {
                List<Para> list = new List<Para>();
                Para para = new Para();
                para.A = Request.Query["A"];
                para.B = Request.Query["B"];
                list.Add(para);
                return Response.AsJson(para);  //会自动转JSON 

            });


            Post("/data", x =>
            {
                // 获取 POST 的 JSON 字符串
                if (this.Request.Body.CanRead)
                {
                    this.Request.Body.ReadByte();
                }
                var jsonStr = GetStreamStr(this.Request.Body);

                //string name = Request.Form["name"];
                //string age = Request.Form["age"];

                string readString = jsonStr;

                Para para = new Para();
                para.A = this.Request.Form["A"];
                para.B = this.Request.Form["B"];

                return Response.AsJson(para);  //会自动转JSON
            });

        }

        public string GetStreamStr(Stream stream)
        {
            string readString = "";
            if (stream.CanRead)
            {
                stream.Position = 0;
                byte[] readBuffer = new byte[stream.Length];
                int count = stream.Read(readBuffer, 0, readBuffer.Length);

                //首先通过流读出的readBuffer的数据求出从相应Char的数量
                int charCount = Encoding.Default.GetCharCount(readBuffer, 0, count);
                //通过该Char的数量 设定一个新的readCharArray数组
                char[] readCharArray = new char[charCount];
                //Encoding 类的强悍之处就是不仅包含加密的方法,甚至将解密者都能创建出来(GetDecoder()),
                //解密者便会将readCharArray填充(通过GetChars方法,把readBuffer 逐个转化将byte转化成char,并且按一致顺序填充到readCharArray中)
                Encoding.Default.GetDecoder().GetChars(readBuffer, 0, count, readCharArray, 0);
                for (int i = 0; i < readCharArray.Length; i++)
                {
                    readString += readCharArray[i];
                }
                stream.Close();
            }
            return readString;

        }


        public class JsonReslut<T> where T : class
        {
            public int result { get; set; }

            public T Obj { get; set; }
        }

        public class Para
        {
            public string A { get; set; }

            public string B { get; set; }

        }

    }

2 页面代码

 public partial class Nancy_Form : Form
    {
        public Nancy_Form()
        {
            InitializeComponent();
        }

        private NancyHost host;

        //开始
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (host != null)
                {
                    richTextBox1.AppendText("已经启动 \r\n");
                    return;
                }
                //Nancy Self Host 必须加上 AutomaticUrlReservationCreation, 否则 host.Start()会报异常
                HostConfiguration hostConfigs = new HostConfiguration()
                {
                    UrlReservations = new UrlReservations() { CreateAutomatically = true }
                }; 
                // 创建 NancyHost 实例
                host = new NancyHost(new Uri("http://localhost:8082"), new DefaultNancyBootstrapper(), hostConfigs); 
                // 启动 NancyHost
                host.Start();
                richTextBox1.AppendText("Running on http://localhost:8082 \r\n");

            }
            catch (Exception ex)
            {
                richTextBox1.AppendText("站点启动失败:" + ex.Message);
            }

        }

        //关闭
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (host == null)
                {
                    richTextBox1.AppendText("站点已经停止 \r\n");
                    return;
                }
                // 停止 NancyHost
                host.Stop();
                host = null;
                richTextBox1.AppendText("站点已经停止 \r\n");
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText("站点停止失败," + ex.Message);
            }
        }

    }

简单写到这里!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值