Nancy(一)简单自宿主HTTP接口

ASP.NET是个牛逼哄哄的框架,固然能够向外提供HTTP接口功能(这里我没有用WebAPI,是由于ASP.NET把WebAPI这么恰当的一 个名词给占用了,因此这里我用HTTP接口代之),但若是你像我同样喜欢简单,不喜欢IIS的话,Nancy自宿主是一个挺不错的选择。

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

相关文章
相关标签/搜索