如何在C#中获取URL路径

27

我想获取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, ""));

在执行 new System.IO.FileInfo(sPath) 时,由于 sPath 包含 "localhost/red/green/default.aspx",导致出现异常,提示 "The given path's format is not supported."。
5个回答

104

主要网址: http://localhost:8080/mysite/page.aspx?p1=1&p2=2

C#中获取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
如果你正在处理的是当前请求中没有的Url,只需要使用 new Uri(myUrlString); 然后利用这些属性。 - AaronLS
2
不,这是一个误导性的答案,因为它与问题的上下文没有关联,具体涉及任何URL,而不仅仅是ASP.NET Web应用程序中可用的当前请求URL。 - Thomas Williams

12

不要把它视为URI问题,而是视为字符串问题。这样做会更加清晰易懂。

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

真的很容易!

编辑后添加丢失的括号。


7
这很危险,Shibu Thomas的回答更好。例如,考虑URL中查询字符串或片段包含“/”的情况。 - Kuba Beránek
新 Uri(...).OriginalString 和 ...AsboluteUri.ToString() 有什么区别? - eaglei22
不适用于所有URI...您假设字符串中会有一个/,但有效的URI可能只是在末尾有查询字符串... - Egli Becerra

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, ""));

2

使用这个

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, ""));

0

如果你只是想在网站上导航到另一个页面,这可能会帮到你,但如果你真的需要绝对路径,它就无法提供。你可以在不使用绝对路径的情况下在网站内导航。

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路径的好文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接