簡體   English   中英

從Request.Url.AbsolutePath獲取應用程序相對URL

[英]Get app relative url from Request.Url.AbsolutePath

如何從Request.Url.AbsolutePath獲取應用程序相對URL?

VirtualPathUtility似乎只適用於~/XXX網址?

它的回答有點晚,但有一個優雅的解決方案。 您可以使用

Request.Url.PathAndQuery

這將返回頁面的相對路徑。

例如,如果網址是www.example.com/products?A=a&B=b&C=c ,則上面的代碼將返回/products?A=a&B=b&C=c

我這樣解決了:

// create an absolute path for the application root
var appUrl = VirtualPathUtility.ToAbsolute("~/");

// remove the app path (exclude the last slash)
var relativeUrl = HttpContext.Current.Request.Url.AbsolutePath.Remove(0, appUrl.Length - 1);

要在不使用字符串操作和處理我使用的應用程序相對路徑的情況下執行此操作:

    var relativeUrl = VirtualPathUtility.ToAppRelative(
        new Uri(context.Request.Url.PathAndQuery, UriKind.Relative).ToString());

這對我有用:

VirtualPathUtility.MakeRelative("~", Request.Url.AbsolutePath)

例如,如果網站的根目錄是/WebsiteRequest.Url.AbsolutePath/Website/some/path則會返回some/path

我認為這是最干凈的方式:

new Uri(Request.Url.PathAndQuery, UriKind.Relative))
 String appUrl = VirtualPathUtility.ToAbsolute("~/");
 String RelativePath = new System.Uri(Page.Request.Url, "").PathAndQuery.Substring(appUrl.Length-1)

在Ashwin Singh的基礎上建立了很好的答案 - 我需要將錨鏈接包含在我的相對URL中,所以我在最后重新添加它:

Request.Url.PathAndQuery + Request.Url.Fragment

所以http://localhost:8080/abc/d?foo=bar#jazz變為/abc/d?foo=bar#jazz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM