2014-10-28 93 views
0

我在global.asa文件中有以下代碼。目標是從URL中獲取分段,然後相應地運行代碼。uriAddress.Segments [1]激發錯誤 - 索引超出了數組的範圍

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

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

不幸的是,如果有在我得到的錯誤是「索引數組的範圍之外」的網址不段。我怎樣才能克服這個錯誤?

+0

'如果(uriAddress.Segments!= NULL && uriAddress.Segments.Length> 1 &&!String.IsNullOrEmpty(uriAddress.Segments [1]))' – Habib 2014-10-28 19:05:39

回答

0

之前試圖讓元素,檢查數組的大小:

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

另外請注意,C#使用從零開始的數組,所以第一個元素是0,而不是1

+0

我已經瞭解到,[0]通常是指你說的第一個元素。這種情況下的第一個元素是斜槓(mydomain.com/)。如何檢查斜槓後面的段是否爲空? – Gloria 2014-10-28 19:02:51

-1

更改'if'語句以檢查Segments數組的長度。

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