Nancy简介

Nancy是一个轻量级的独立的框架,下面是官网的一些介绍:

  • Nancy 是一个轻量级用于构建基于 HTTP 的 Web 服务,基于 .NET 和 Mono 平台,框架的目标是保持尽可能多的方式,并提供一个super-duper-happy-path所有交互。
  • Nancy 设计用于处理 DELETEGETHEADOPTIONSPOSTPUT和 PATCH 等请求方法,并提供简单优雅的 DSL 以返回响应。让你有更多时间专注于你的代码和程序。

官方地址:http://nancyfx.org

GitHub:https://github.com/NancyFx/Nancy

言归正传,下面说说如何用Nancy提供一个自宿主的HTTP接口。

创建 .NET Core Nancy项目

一、新建一个控制台应用程序

二、使用 NuGet 安装所需包

  使用 NuGet 安装 Nancy 和 Nancy.Hosting.Self 两个程序包。导入完成后效果如下:

三、编写宿主启动代码

  打开Program.cs,在Main方法里输入以下代码:

using Nancy;
using Nancy.Hosting.Self;
using System; namespace DotNetNancyDemo
{
class Program
{
static void Main(string[] args)
{
try
{
var url = new Url("http://localhost:22222");
var hostConfig = new HostConfiguration();
hostConfig.UrlReservations = new UrlReservations { CreateAutomatically = true };
using (var host = new NancyHost(hostConfig, url))
{
host.Start(); Console.WriteLine("Your application is running on" + url);
Console.WriteLine("Press any [Enter] to close the host.");
Console.ReadLine();
}
}
catch (Exception ex)
{ }
}
}
}

四、编写接口处理模块

  新建 IndexModule.cs 类文件,让 IndexModule 继承 NancyModule,

  在 IndexModule 的构造函数里编写路由规则及 HTTP 处理, IndexModule 如下:

using Nancy;
using System;
using System.Collections.Generic;
using System.Text; namespace DotNetNancyDemo
{
public class IndexModule:Nancy.NancyModule
{
public IndexModule()
{
Get("/" , x => "Hello World"); Get("/GetPerson/{id:int}" , parameters =>
{
Person p = new Person();
p.ID = parameters.ID;
p.Name = "张三";
return Response.AsJson(p);
});
}
} class Person
{
public string ID { get; set; }
public string Name { get; set; }
}
}

五、运行测试

  打开浏览器 输入:http://localhost:22222/

  载入:http://localhost:22222/getperson/100

注意:需要用管理员打开项目运行,否则会出现如下错误。

  链接: https://pan.baidu.com/s/1iWLoO0zJKla9XlgxLbk_wA

  提取码: k7xs

最新文章

  1. C# 读取XML注释
  2. VMWare安装Solaris虚拟机的网络设置
  3. Hadoop学习10--常用命令记录帖
  4. android 学习随笔二十四(动画:帧动画)
  5. 学习Berkeley DB- 入门
  6. poj 2688 状态压缩dp解tsp
  7. WDatePicker 屏蔽onchange事件的解决办法
  8. Angular.js中的$injector服务
  9. 每天进步一点点之SQL 获取表中某个时间字段离当前时间最近的几条
  10. mysql主从集群配置
  11. ActiveMq报错Channel was inactive for too (>30000)long
  12. 某神秘公司 RESTful、共用接口、前后端分离、接口约定的实践
  13. Spring Boot 静态资源访问原理解析
  14. YIi url美化
  15. python基础知识回顾之字符串
  16. 1021 Deepest Root
  17. tf.argmax()以及axis解析
  18. mysql 连表查询
  19. CI框架 -- 核心文件 之 Benchmark.php
  20. python抓取链家房源信息(三)

热门文章

  1. 浏览器绘图模型的解释:renderObject、renderlayer
  2. 修改mysql 8.0.16 root 密码--mac
  3. 7-zip命令行详解
  4. expr算术运算
  5. RPM包——查询
  6. chart.xkcd 可绘制粗略,开通,手绘样式的图表库
  7. 常用方法 DataTable转换为Entitys
  8. 驱动中遍历模块,以及获取ntoskrnl.exe基址
  9. putty WinScp 免密登录远程 Linux
  10. 第01组 Alpha冲刺(1/6)