2009-07-10 31 views
0

可以說我有一個絕對url /testserver/tools/search.aspx,我存儲在一個變量url中。如何獲得以下字符串的一部分?

我想檢查url == /tools/search.aspx而不必使用/ testserver。

更完整的例子是:

我TESTSERVER包含URL http://www.testserver.com/tools/Search.aspx

但我活的服務器包含URL http://www.liveserver.com/tools/Search.aspx

如果我比較變量URL存儲的TESTSERVER網址liveserver url,它會失敗,這就是爲什麼我只想檢查/tools/Search.aspx部分。

+0

正則表達式,也許? – thebrokencube 2009-07-10 17:27:53

+0

您的網址是`/ testserver/tools/search.aspx`還是`http://www.testserver.com/tools/Search.aspx`? – dtb 2009-07-10 17:30:05

+0

當我調試並檢查AbsoulteUrl時是/testserver/tools/search.aspx – Xaisoft 2009-07-10 17:32:10

回答

2
if (url.ToLower().Contains("/tools/search.aspx")) 
{ 
    //do stuff here 
} 

我會用包含如果你有一個查詢字符串,但你也可以使用的endsWith(「/工具/ search.aspx」),如果你沒有查詢字符串。

0

您可以使用屬性AppRelativeCurrentExecutionFilePath,它將爲您提供相對於應用程序根目錄的路徑。所以"http://host/virtualfolder/page.aspx""~/page.aspx"

if (HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/search.aspx", StringComparison.InvariantCultureIgnoreCase)) 
{ 
    // do something 
} 
3

如果輸入的形式是"http://www.testserver.com/tools/Search.aspx"的:

var path1 = new Uri("http://www.testserver.com/tools/Search.aspx").AbsolutePath; 
var path2 = new Uri("http://www.liveserver.com/tools/Search.aspx").AbsolutePath; 

兩個結果"/tools/Search.aspx"

使用Uri是最好的解決方案,如果您有接受任何URI,即包括那些具有查詢字符串,片段標識符等


如果輸入的形式爲「/ TESTSERVER的。 COM /工具/ Search.aspx」 你知道,所有的輸入將永遠是這種形式,有效的並且不包含其他URI成分:

var input = "/testserver.com/tools/Search.aspx"; 
var path1 = input.Substring(input.Index('/', 1)); 

結果是"/tools/Search.aspx"

1
Regex.Match(url, @"^.*?/tools/search\.aspx\??.*", 
       RegexOptions.IgnoreCase).Success == true 

如果你抓住從Request的PathInfo你不會有域反正網址...但你的問題是模糊的,因爲你說你有一個路徑/ TESTSERVER /一,但不是在你的網址提供。

否則,Request.Url.ToString()

0

如果唯一的區別將是URL的主機部分我會用System.Uri類比較他們絕對路徑(以下簡稱「設置網址tools/Search.aspx「的一部分)。

下面是如何做到這一點的例子:

static void Main(string[] args) 
{ 
    //load up the uris 
    Uri uri = new Uri("http://www.testserver.com/tools/search.aspx");    
    Uri matchingUri = new Uri("http://www.liveserver.com/tools/search.aspx"); 
    Uri nonMatchingUri = new Uri("http://www.liveserver.com/tools/cart.aspx"); 

    //demonstrate what happens when the uris match 
    if (uri.AbsolutePath == matchingUri.AbsolutePath) 
     Console.WriteLine("These match"); 
    //demonstrate what happens when the uris don't match 
    if (uri.AbsolutePath != nonMatchingUri.AbsolutePath) 
     Console.WriteLine("These do not match"); 
} 
相關問題