none
How to check if Segments is exist? RRS feed

  • General discussion

  • Hi,

    I am using below to split URL

    var query = uri.PathAndQuery.Trim(new[] { '/' });
    
    string page = uri.Segments[1].Trim(new[] { '/' });
    the_id = uri.Segments[2].Trim(new[] { '/' });


    But I want first to check if the id is exist

    I tried this but did not work:

    var query = uri.PathAndQuery.Trim(new[] { '/' });
    
    string page = uri.Segments[1].Trim(new[] { '/' });
    
    if (!string.IsNullOrWhiteSpace(uri.Segments[2])
    {
         the_id = uri.Segments[2].Trim(new[] { '/' });
    }
    


    Kindly help..

    Thanks,

    Jassim


    Wednesday, October 2, 2019 8:36 PM

All replies

  • Shouldn't you check for the .Length of uri.Segments first?

    If it's not supplied, you'll get one less segment, not same number of segment with last element set to null.

    Of course you'll want to check for whitespace. However depend on webserver implementation, some may just remove the adjecent '/' if "//" is found, I think.

    Thursday, October 3, 2019 1:48 AM
    Answerer
  • Hi,

    I am trying:

    if (!string.IsNullOrWhiteSpace(uri.Segments[2])) the_id = uri.Segments[2].Trim(new[] { '/' });


    and:

    if (uri.Segments[2].Length > 0) the_id = uri.Segments[2].Trim(new[] { '/' });

    They both works fine for this URL:

    https://www.domain.com/news/1234

    but crashing for this URL:

    https://www.domain.com/news

    with this error:

    System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

    Saturday, October 12, 2019 1:16 AM
  • I told you to check the length of uri.Segments first:

                if ((uri.Segments.Length > 2) && (!String.IsNullOrWhiteSpace(uri.Segments[2])))
                    the_id = uri.Segments[2].Trim(new[] { '/' });
    

    Sunday, October 13, 2019 2:14 PM
    Answerer