Подтвердить что ты не робот

Как получить URL-путь в С#

Я хочу получить весь путь URL, кроме текущей страницы url, например: мой URL http://www.MyIpAddress.com/red/green/default.aspx Я хочу получить "http://www.MyIpAddress.com/red/green/". Как я могу получить. Я делаю как

string sPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString; System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            sPath = sPath.Replace("http://", "");
            System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
            string sRet = oInfo.Name;
            Response.Write(sPath.Replace(sRet, ""));

Показывая исключение в новом System.IO.FileInfo(sPath), поскольку sPath содержит "localhost/red/green/default.aspx", говорящий: "Данный формат пути не поддерживается".

4b9b3361

Ответ 1

Не рассматривайте его как проблему с URI, рассматривайте его как строку. Тогда это приятно и легко.

String originalPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString;
String parentDirectory = originalPath.Substring(0, originalPath.LastIndexOf("/"));

Действительно, это легко!

Отредактировано, чтобы добавить отсутствующую скобку.

Ответ 2

Основной URL: http://localhost:8080/mysite/page.aspx?p1=1&p2=2

Получить разные части URL-адреса на С#.

Value of HttpContext.Current.Request.Url.Host
localhost

Value of HttpContext.Current.Request.Url.Authority
localhost:8080

Value of HttpContext.Current.Request.Url.AbsolutePath
/mysite/page.aspx

Value of HttpContext.Current.Request.ApplicationPath
/mysite

Value of HttpContext.Current.Request.Url.AbsoluteUri
http://localhost:8080/mysite/page.aspx?p1=1&p2=2

Value of HttpContext.Current.Request.RawUrl
/mysite/page.aspx?p1=1&p2=2

Value of HttpContext.Current.Request.Url.PathAndQuery
/mysite/page.aspx?p1=1&p2=2

Ответ 3

Заменить это:

            string sRet = oInfo.Name;
            Response.Write(sPath.Replace(sRet, ""));

Со следующим:

        string sRet = oInfo.Name;           
        int lastindex = sRet.LastIndexOf("/");
        sRet=sRet.Substring(0,lastindex)
        Response.Write(sPath.Replace(sRet, ""));

Ответ 4

используйте этот

string sPath = (HttpContext.Current.Request.Url).ToString();
sPath = sPath.Replace("http://", "");
var oInfo = new  System.IO.FileInfo(HttpContext.Current.Request.RawUrl);
string sRet = oInfo.Name;
Response.Write(sPath.Replace(sRet, ""));

Ответ 5

Это может заставить вас хотеть, чтобы вы захотели, если вы просто пытаетесь перейти на другую страницу своего сайта, но она не получает абсолютного пути, если вам это действительно нужно. Вы можете перемещаться по сайту без использования абсолютного пути.

string loc = "";
loc = HttpContext.Current.Request.ApplicationPath + "/NewDestinationPage.aspx";
Response.Redirect(loc, true);

Если вам действительно нужен абсолютный путь, вы можете выбрать части и построить то, что вам нужно, с классом Uri:

Uri myUri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri)
myUri.Scheme
myUri.Host  // or DnsSafeHost
myUri.Port
myUri.GetLeftPart(UriPartial.Authority)  // etc.

Хорошая статья в отношении путей ASP.NET.