1. 程式人生 > >OWIN 自托管靜態網站

OWIN 自托管靜態網站

help sop 中間 psu 服務器監控 小工具 fault lob post

我們知道,借助OWIN,WebApi,SignalR,WCF 都可以創建自托管(Self-Host)實例,完全不需要IIS,靜態網站也可以。

最近做一個服務器監控小工具,用 SignalR 通信,監控端是一個靜態網站(掛在IIS),服務端是一個 WinForm 程序(SignalR 服務寄宿),但是我想網站也寄宿到這個 WinForm 中,這樣通過 WebApp.Start 開啟主機時,網站也開啟了,部署也方便

為了減少配置代碼,我們用一個靜態文件處理的中間件 Beginor.Owin.StaticFile

Install-Package Beginor.Owin.StaticFile

在 OWIN 啟動類中配置

using Beginor.Owin.StaticFile;

[assembly: OwinStartup(typeof(AisinGioro.Server.OwinStartup))]
namespace AisinGioro.Server
{
    public class OwinStartup
    {
        public void Configuration(IAppBuilder app)
        {
            //靜態文件托管
            app.Map("/wwwroot", map =>
            {
                
// 允許跨域 map.UseCors(CorsOptions.AllowAll); map.UseStaticFile(new StaticFileMiddlewareOptions { RootDirectory = @"D:\P22\Felix\AisinGioro\AisinGioro.WebPortal", DefaultFile = "index.html", EnableETag
= true, EnableHtml5LocationMode = true, MimeTypeProvider = new MimeTypeProvider(new Dictionary<string, string> { { ".html", "text/html" }, { ".htm", "text/html" }, { ".dtd", "text/xml" }, { ".xml", "text/xml" }, { ".ico", "image/x-icon" }, { ".css", "text/css" }, { ".js", "application/javascript" }, { ".json", "application/json" }, { ".jpg", "image/jpeg" }, { ".png", "image/png" }, { ".gif", "image/gif" }, { ".config", "text/xml" }, { ".woff2", "application/font-woff2"}, { ".eot", "application/vnd.ms-fontobject" }, { ".svg", "image/svg+xml" }, { ".woff", "font/x-woff" }, { ".txt", "text/plain" }, { ".log", "text/plain" } }) }); }); //SignalR托管 app.Map("/signalr", map => { // 允許跨域 map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { //Resolver = **, // You can enable JSONP by uncommenting line below. // JSONP requests are insecure but some older browsers (and some // versions of IE) require JSONP to work cross domain EnableJSONP = true, EnableDetailedErrors = true }; // Run the SignalR pipeline. We‘re not using MapSignalR // since this branch is already runs under the "/signalr" // path. map.RunSignalR(hubConfiguration); }); //該值表示連接在超時之前保持打開狀態的時間長度。 //默認為110秒 //GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(110); //該值表示在連接停止之後引發斷開連接事件之前要等待的時間長度。 //默認為30秒 GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(60); } } }

其中 RootDirectory 也可以配置相對目錄,比如 ../app/wwwroot

MimeTypeProvider 屬性設置 MIME 映射(Content-Type),如果不設置,Beginor.Owin.StaticFile 只能能判斷普通的類型(比如 html,css,js),所以還是設置下比較好

創建Web服務監聽,開啟主機

private void DoWork()
        {
            try
            {
                //創建WEB服務器監聽
                using (WebApp.Start<OwinStartup>(_hostUrl))
                {
                    if (this.OnStartSucceed != null)
                        this.OnStartSucceed(this, EventArgs.Empty);

                    LogHelper.Trace("Server started! {0}", _hostUrl);

                    while (!cancelTokenSource.IsCancellationRequested)
                        Thread.Sleep(10);
                }

                LogHelper.Trace("Server stopped!");

                if (this.OnStopSucceed != null)
                    this.OnStopSucceed(this, EventArgs.Empty);  //Server stopped!
            }
            catch (Exception ex)
            {
                ex = ex.GetBaseException();
                LogHelper.Error(ex.Message + " " + _hostUrl);

                if (this.OnFailed != null)
                    this.OnFailed(this, new ErrorOccuredEventArgs(ex));
            }
        }

如果外部程序執行 cancelTokenSource.Cancel,主機服務停止運行

=========================

客戶端連接SignalR用這個地址:http://localhost:9000/signalr

而訪問網站,用這個地址:http://localhost:9000/wwwroot/

OWIN 自托管靜態網站