官方:http://nancyfx.org/ c#
下面說說如何用Nancy提供一個自宿主的HTTP接口。 瀏覽器
1、新建一個控制檯應用程序 app
注意是控制檯應用程序,不是空的WebForm或空的MVC項目。 框架
2、用NuGet安裝所需包 函數
用NuGet安裝Nancy和Nancy.Hosting.Self兩個程序包。 測試
3、編寫宿主啓動代碼 url
打開Program.cs,在Main方法裏輸入如下代碼: spa
var url = new Url("http://localhost:9955"); 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(); }
4、編寫接口處理模塊 code
新建IndexModule.cs類文件,讓IndexModule繼承NancyModule, orm
在IndexModule的構造函數裏編寫路由規則及HTTP處理,IndexModule以下:
public class IndexModule:NancyModule { public IndexModule() { Get["/"] =_=> "Hello World"; Get["/GetPerson/{id:int}"] = parameters => { Person p = new Person(); p.ID = parameters.ID; p.Name = "loogn"; return Response.AsJson(p); }; } } public class Person { public int ID { get; set; } public string Name { get; }
5、運行測試
Ctrl+F5啓動服務
打開瀏覽器 輸入:http://localhost:9955/
載入:http://localhost:9955/getperson/26