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