asp.net擷取網站絕對路徑案例詳解

來源:互聯網
上載者:User

 在編寫 ASP.NET 應用程式的時候,有時為了更好地進行控制靜態檔案的路徑,如在模板頁或者使用者控制項中設定js或者css檔案的路徑等,採用絕對路徑是難免的。下面就是幾種擷取絕對路徑的幾種方法

 代碼如下:VirtualPathUtility.ToAbsolute( " ~/ " )HttpRuntime.AppDomainAppVirtualPathRequest.ApplicationPathPage.ResolveUrl( " ~ " )  以上代碼產生的結果如下:當以網站的方式訪問時,結果如下:   代碼如下:VirtualPathUtility.ToAbsolute("~/") = /HttpRuntime.AppDomainAppVirtualPath = /Request.ApplicationPath = /Page.ResolveUrl("~") = /  當以虛擬目錄(http://localhost:806/web2/url.aspx)訪問時,結果如下: 代碼如下:VirtualPathUtility.ToAbsolute("~/") = /web2/HttpRuntime.AppDomainAppVirtualPath = /web2Request.ApplicationPath = /web2Page.ResolveUrl("~") = /web2/  採用第二種和第三種方法,還需要做一下處理,因為網站訪問時是以/結尾,而以虛擬目錄訪問時則是沒有/的,進行還得進行一次判斷,稍微麻煩一點。但是,這些方法在頁面中使用是沒有任何問題的,但是如果在 Global 的 Application_Start 事件裡需要得到網站的絕對路徑,則需要使用前面2種方法,如果使用第三種方法,則會報告如下的錯誤:Request is not available in this context 所以,只能採取頭2種方法。例如 代碼如下:void Application_Start( object sender, EventArgs e){    System.IO.StreamWriter s = new System.IO.StreamWriter(HttpRuntime.AppDomainAppPath + " log.txt " );    s.WriteLine(VirtualPathUtility.ToAbsolute( " ~/ " ));    s.WriteLine(HttpRuntime.AppDomainAppVirtualPath);    s.Close();} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.