
正文
.NET Core 之 Nancy 基本使用
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Nancy简介
Nancy是一个轻量级的独立的框架,下面是官网的一些介绍:
- Nancy 是一个轻量级用于构建基于 HTTP 的 Web 服务,基于 .NET 和 Mono 平台,框架的目标是保持尽可能多的方式,并提供一个super-duper-happy-path所有交互。
- Nancy 设计用于处理
DELETE,GET,HEAD,OPTIONS,POST,PUT和 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







