下面说说如何用Nancy提供一个自宿主的HTTP接口。
一、新建一个控制台应用程序
注意是控制台应用程序,不是空的WebForm或空的MVC项目。
二、用NuGet安装所需包
用NuGet安装Nancy和Nancy.Hosting.Self两个程序包。
三、编写宿主启动代码
打开Program.cs,在Main方法里输入以下代码:
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();
}
四、编写接口处理模块
新建IndexModule.cs类文件,让IndexModule继承NancyModule,
在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;
}
五、运行测试
Ctrl+F5启动服务

打开浏览器 输入:http://localhost:9955/
载入:http://localhost:9955/getperson/26