Request.Url.Segments[3]
returns pagename. at my demo server have IIS6
and its working fine but at my live server had installed IIS7
and Request.Url.Segments[3]
does not return page name it开发者_JAVA技巧 gives an error.
Please help me. Thanks in advance
This has nothing to do with the version of IIS. Most likely, you have a different setup for the site.
For example, on dev, by default on Visual Studio F5 debug, the site runs at:
http://localhost:1234/sitename/folder/page.aspx
|\_______/\_____/\_______/
0 1 2 3
On test/production, you may not have the first folder:
http://sitename.corpo.com/folder/page.aspx
|\_____/\_______/
0 1 2
There are better ways of getting the last element of an array dynamically, even without knowing its length. Try using:
Request.Url.Segments.Last()
Or, without linq,
Request.Url.Segments[Request.Url.Segments.Length - 1]
If you are not looking for the last element, you may have to come up with a better way of specifying what you need.
The value for each item in .Segments
is entirely dependent on the Url, which is dictated by how the site is set up in IIS.
For instance, having your site at the root of the webserver will give different reseults to having the site under a virtual root.
In the url http://myserver/mypage.aspx, the page is at item index 1. In the url http://myserver/myvirtualroot/mypage.aspx, the page is at item index 2.
You can demostrate this for yourself as follows:
var uri = new Uri("http://myserver/mypage.aspx");
for (var i = 0; i < uri.Segments.Length; i++)
{
Console.WriteLine("Segments[{0}]: {1}",i, uri.Segments[i]);
}
This gives:
Segments[0]: /
Segments[1]: mypage.aspx
now try it again for
var uri2 = new Uri("http://myserver/myvirtualroot/mypage.aspx");
this time you'll get:
Segments[0]: /
Segments[1]: myvirtualroot/
Segments[2]: mypage.aspx
The point is that you can't reliably say "item index 3 is the page" unless you know that the actual site url (and hence its configuration in IIS) is the same across environments. (Even then. it is not a particularly nice way of doing it as it is so brittle to changes)
As Kobi points out, simply using uri.Segments.Last() will get you the last segment (without the querystring if there is one) which is exactly what you want.
精彩评论