如何在C#中获取URL路径

Nom*_*Ali 19 .net c# asp.net 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, ""));
Run Code Online (Sandbox Code Playgroud)

它在新的System.IO.FileInfo(sPath)上显示异常,因为sPath包含"localhost/red/green/default.aspx",表示"不支持给定路径的格式".

Shi*_*mas 76

主要网址: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
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在处理不在当前请求中的 Url,只需 `new Uri(myUrlString);` 然后利用这些属性。 (3认同)
  • 不。这是一个**误导性**答案,因为它与问题的上下文无关,特别是与任何 URL 相关,而不仅仅是 ASP.NET Web 应用程序中可用的当前请求 Url。 (2认同)

jwa*_*jwa 13

不要将其视为URI问题,将其视为字符串问题.然后它很好很容易.

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

真的很容易!

编辑添加缺失的括号.

  • 这很危险,Shibu Thomas'[回答](http://stackoverflow.com/a/35194130/1107768)更好.例如,考虑URL在查询字符串或片段中包含"/"的情况. (3认同)