官方: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