在新版本的BeetleX.FastHttpApi
加入了對netstandard2.0
支持,如果程序基於.NetFramework4.6.1來構建WinForm或WPF桌面程序的情況下可以直接把BeetleX的HTTP嵌入到程序中,輕易就能實現一個本地化的HTTP服務並提供靜態資源和WebAPI的調用處理;以下簡單地介紹在WinForm/WPF引入BeetleX.FastHttpApi
的HTTP服務。
引用Beetlex
組件在1.4.5.8
版本后加入了對netstandard2.0
的支持,只需要在Nuget上添加這個或更高版的BeetleX.FastHttpApi
即可
添加代碼
只需要幾行代碼即可在程序中添加HTTP服務
private BeetleX.FastHttpApi.HttpApiServer mHttpApiServer; private void Form1_Load(object sender, EventArgs e) { SetIE(); mHttpApiServer = new BeetleX.FastHttpApi.HttpApiServer(); mHttpApiServer.Register(typeof(Form1).Assembly); mHttpApiServer.Open(); }
構建一個HttpApiServer對象,然后把當前程序集注冊到服務中即可完成。
服務配置
"HttpConfig": { "Host": "", "Port": 12345, "SSL": false, "CertificateFile": "", "CertificatePassword": "", "MaxBodyLength": 20097152, "OutputStackTrace": true, "StaticResurceType": "xml;svg;woff;woff2;jpg;jpeg;gif;png;js;html;htm;css;txt;ico;zip;rar", "DefaultPage": "index.html;index.htm", "NotLoadFolder": "\\Files;\\Images;\\Data", "NoGzipFiles": "xml;svg;woff;woff2;jpg;jpeg;gif;png;js;html;htm;css;txt;ico;zip;rar", "CacheFiles": "", "BufferSize": 8192, "WebSocketMaxRPS": 2000, "WriteLog": true, "LogToConsole": true, "LogLevel": "Warring" }
默認配置是在端口12345上開啟http
和websocket
服務;運行程序后可以通過瀏覽器訪問http://localhost:12345
即可訪問服務。不過更多情況是程序內嵌一個webBrowser打開,這樣即可完全使用html+css+js來構建一個本地UI程序了。
靜態資源添加
組件通過目錄名來約束資源存儲位置,所有資源必須存放在程序的views目錄下
靜態文件屬性設置成嵌入程序或編譯復制的方式進行發布,程序可以在webBrowser設置服務地址即可打開網頁,效果如下:
通過這種集成方式WinForm/WPF就完全可以用html+css+vue等這些功能進行windows程序UI開發。
定義Webapi
如果使用內嵌的http+html+css+vue做桌面應用開發,那必然也需要有數據交互的接口;接下來簡單地定義一個接口讓javascript訪問
[Controller] public class WebAction { public object GetStarted(string email) { return new TextResult($"{email} {DateTime.Now}"); } }
只需要在項目中簡單地添加一個控制器即可,以上GetStarted
訪問的訪問路徑是/GetStarted
;通過ajax在頁面調用的腳本
function GetStarted(email) { $.get('/GetStarted?email=' + email, function (result) { alert(result); }); }
以上是WinForm/WPF內嵌BeetleX構建的一個桌面應用,是不是感覺很簡單?如果你對Beetlex感興趣可以關注 https://github.com/IKende/FastHttpApi
完整示例代碼
https://github.com/IKende/FastHttpApi/tree/master/samples/WinWebSample