ASP.NET MVC 中全局獲取項目根目錄
- 2019 年 12 月 9 日
- 筆記
在處理請求的適合經常會出現url異常的狀況,導致頁面的加載出錯。主要原因的是在判斷url路徑的時候,本地的測試環境的路徑和實際的IIS的發佈路徑並不相同,因此通過在Shared/Layout 中配置獲取,並直接在頁面中使用。
//配合 Shared/layout 獲取根路徑,用於請求鏈接 window.ROOT = "@HttpContext.Current.Request.ApplicationPath"; if (window.ROOT != "/") { window.ROOT += "/"; } //Shared/layout中獲取頁面的 路徑
utils.getRoot = function() { if (window.ROOT) return window.ROOT; if (layui.ROOT) return layui.ROOT; }
在非js腳本中使用,則可以使用原本的 Razor 方法。
@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")