2009-07-10 33 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"); 
} 
相关问题