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