0

I have the following code in the global.asa file. The aim is to get the segments from the URL and then run codes accordingly.

protected void Application_BeginRequest(object sender, EventArgs e)
{
Uri uriAddress = new Uri(Request.Url.AbsoluteUri);

        if (!String.IsNullOrEmpty(uriAddress.Segments[1]))
        {
           //do stuff
        }
 }

Unfortunately if there are no segments in the URL I get the error that "Index was outside the bounds of the array". How can I overcome this error?

Gloria
  • 1,305
  • 5
  • 22
  • 57
  • `if (uriAddress.Segments != null && uriAddress.Segments.Length > 1 && !String.IsNullOrEmpty(uriAddress.Segments[1]))` – Habib Oct 28 '14 at 19:05

2 Answers2

0

Before trying to get the element, check the size of the array:

if (uriAddress.Segments.Length > 0) { 
    var segment = uriAddress.Segments[0];
}

Also, note that C# uses zero-based arrays, so the first element would be 0, not 1.

Nathan A
  • 11,059
  • 4
  • 47
  • 63
  • I've learned that [0] usually refers to the first element as you said. The first element in this case is the slash (mydomain.com/). How can I check if the segment after the slash is not empty? – Gloria Oct 28 '14 at 19:02
-1

Change your 'if' statement to check the length of the Segments array.

if(uriAddress.Segments.Length > 0 && !String.IsNullOrEmpty(uriAddress.Segments[1]))
{
   //do stuff
}