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

相關文章
相關標籤/搜索