Asp.net

如何為 Katana/Owin 自託管應用程序設置預設靜態網頁?

  • January 1, 1

我已經使用 Owin 自託管控制台應用程序建立了一個網站。我提供的靜態文件沒有問題,網站靜態部分的“根”工作正常,Web API 路由也工作正常。

如果我瀏覽到:

http://localhost/index.html

它呈現了我所期望的一切。但我還沒有想出如何設置它以便瀏覽到:

http://localhost

呈現 index.html(作為預設視圖)。這只是在 IIS 樣式的站點下工作。如何使其與 Owin 自助主機一起使用?

我這樣做:

var physicalFileSystem = new PhysicalFileSystem(webPath);
var options = new FileServerOptions
                         {
                             EnableDefaultFiles = true,
                             FileSystem = physicalFileSystem
                         };
       options.StaticFileOptions.FileSystem = physicalFileSystem;
       options.StaticFileOptions.ServeUnknownFileTypes = true;
       options.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" };
       appBuilder.UseFileServer(options);

fra的答案的更詳細版本:

1- NuGet 安裝 Microsoft.Owin.StaticFiles(我假設您已經通過 NuGet 安裝了 Microsoft.AspNet.WebApi.OwinSelfHost)

2- 在您的解決方案中(在 Visual Studio 中)創建一個目錄,並將所有客戶端文件放入其中,例如

+Web

--+images

--+pages

------page1

------page2

--+scripts

--+css

---index.html

注意:有一個根目錄(web)包含所有其他目錄,以及根目錄下的index.html。

3- 現在,在包含您的 Web api 路由配置的同一類中,添加以下程式碼:

var physicalFileSystem = new PhysicalFileSystem(@".\Web"); //. = root, Web = your physical directory that contains all other static content, see prev step
var options = new FileServerOptions
{
   EnableDefaultFiles = true,
   FileSystem = physicalFileSystem
};
options.StaticFileOptions.FileSystem = physicalFileSystem;
options.StaticFileOptions.ServeUnknownFileTypes = true;
options.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" }; //put whatever default pages you like here
appBuilder.UseFileServer(options);

4- 上一個程式碼工作的另一個步驟:確保將Copy to output directoryWeb 目錄(以及所有嵌套目錄)中所有文件的屬性設置為Copy Always[選擇文件 | 按 F4,或右鍵點擊屬性 | 去Copy to output directory]

就這樣 :)

引用自:https://stackoverflow.com/questions/25478222