我有两个字符串:
string url = HttpContext.Current.Request.Url.AbsoluteUri;
//give me :
//url = http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15
并且:
string path = HttpContext.Current.Request.Url.AbsolutePath;
//give me:
//path = /TESTERS/Default6.aspx
现在我想得到字符串:
http://localhost:1302
所以我想的是我会在url中找到路径的位置,并从url中的这个位置移除子字符串。 我尝试了什么:
string strApp = url.Remove(url.First(path));
或
string strApp = url.Remove(url.find_first_of(path));
但是我无法找到表达这个想法的写作方式。我如何归档我的目标?
答案 0 :(得分:3)
所以基本上你需要从开始到你的路径开头的URL。
您不需要"删除"那个部分,只将角色带到那个精确点。首先,您可以使用简单的IndexOf
获取该位置,因为它返回与您的字符串匹配的第一个字符的位置。在此之后,只需将url
的{{1}}部分转换为0
的索引。
Substring
您可以缩短为
string url = "http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15";
string path = "/TESTERS/Default6.aspx";
int indexOfPath = url.IndexOf(path);
string strApp = url.Substring(0, indexOfPath); // gives http://localhost:1302
答案 1 :(得分:0)
您还可以执行类似以下代码的操作来获取URI主机
Uri uri =HttpContext.Current.Request.Url.AbsoluteUri ;
string host = uri.Authority; // "example.com"
答案 2 :(得分:0)
这是另一种选择..这不需要任何字符串操作:
new Uri(HttpContext.Current.Request.Url, "/").AbsoluteUri
它会生成一个新的Uri,即路径" /"相对于原始的Url
答案 3 :(得分:0)
你应该只使用它:
string baseURL = HttpContext.Current.Context.Request.Url.Scheme + "://" +
HttpContext.Current.Context.Request.Url.Authority;
答案 4 :(得分:0)
这不应该使用字符串操作来解决。 HttpContext.Current.Request.Url
会返回Uri object,它有能力返回您请求的信息。
var requestUrl = HttpContext.Current.Request.Url;
var result = requestUrl.GetComponents(UriComponents.SchemeAndServer,
UriFormat.Unescaped);
// result = "http://localhost:1302"