.net Nancy自宿主的使用
發表時間:2020-9-24
發布人:葵宇科技
瀏覽次數:39
Nancy是.net中一款非常輕巧的開源框架,它小巧但卻不簡單,NancyFx不只是一個用于構建Web站點或API節點的Web框架。它是一個完整的框架,可提供基于Http的服務功能,可以構建簡單控制臺程序,也可以搭建大型的企業網站。
也就是說,我們可以不采用IIS而是通過控制臺程序完成整個服務的構建。聽起來是不是牛逼哄哄的?沒錯,的確是這樣,雖然還有很多小白朋友不知道如何用它來構建控制臺程序,但今天小編就給大家分享一下nancy中自宿主的使用方法。
一、新建一個控制臺應用程序
注意是控制臺應用程序,不是空的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
上面就是今天給大家分享的如何用Nancy提供一個自宿主的HTTP接口的詳細方法。更多技術文章請關注云南網站制作-葵宇科技官方網站。