2010-01-15 87 views
1

在配置文件的自定義配置部分中,我想讓屬性或元素爲服務端點定義新方案,主機和端口,但不定義路徑。 所以這些應該被允許https://newhost/http://newhost:800,但不是newhost:800,http://newhost/path/to/service使用ConfigurationValidator或其他驗證程序驗證Uri

什麼是實施的最佳選擇?

感覺就像應該有一個Uri.Parse,UriParser的一個很好的重載,它會讓它變得容易。有沒有我錯過的UriValidator?或者是正則表達式將是最好的選擇(以便它可以很容易地禁止路徑)?

請注意,這不是特定於ConfigurationValidator的,因爲可以重用的一般驗證器會很有用。

回答

2

總有Uri類的GetLeftPart方法可以幫助這裏。

GetLeftPart Method

的GetLeftPart方法需要一個枚舉從UriPartial系統枚舉,其中之一(UriPartial.Authority)將返回:的 的URI

的方案和權威段。

這有效地消除可能在原始字符串的任何外來的路徑信息,並通常會返回一個零長度字符串如果URI供給不包含有效的scheme(即,HTTP或HTTPS等的部件Uri)和/或權威(例如在你的例子中,這是Uri的newhost部分)。

從這裏,您應該能夠將呼叫的返回值與GetLLeftPart與原始Uri字符串進行比較,如果它們不同,則Uri是「無效的」。如果他們是相同的,Uri是「有效的」(爲了您的目的)。

下面是一個簡單的例子類,將執行此 「確認」 返回True或False的URI(C#和VB.NET版本):

C#

public static class UriValidator 
{ 
    public static bool IsUriValid(string uri) 
    { 
     try 
     { 
      string original_uri = uri; 
      if (uri.Substring(uri.Length - 1, 1) == "/") 
      { 
       original_uri = uri.Substring(0, uri.Length - 1); 
      } 
      Uri myUri = new Uri(original_uri); 
      string new_uri = myUri.GetLeftPart(UriPartial.Authority); 
      if (original_uri.ToLower() == new_uri.ToLower()) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 
     catch 
     { 
      return false; 
     }    
    } 
} 

VB 。NET

Public Class UriValidator 
    Public Shared Function IsUriValid(ByVal uri As String) As Boolean 
     Try 
      Dim original_uri = uri 
      If uri.Substring(uri.Length - 1, 1) = "/" Then 
       original_uri = uri.Substring(0, uri.Length - 1) 
      End If 
      Dim myUri As Uri = New Uri(original_uri) 
      Dim new_uri As String = myUri.GetLeftPart(UriPartial.Authority) 
      If original_uri.ToLower = new_uri.ToLower Then 
       Return True 
      Else 
       Return False 
      End If 
     Catch ex As Exception 
      Return False 
     End Try 
    End Function 
End Class 

我跑了一個簡單的測試使用這個類:

Console.WriteLine("https://newhost/" + " " + UriValidator.IsUriValid("https://newhost/")); 
Console.WriteLine("http://newhost:800" + " " + UriValidator.IsUriValid("http://newhost:800")); 
Console.WriteLine("newhost:800" + " " + UriValidator.IsUriValid("newhost:800")); 
Console.WriteLine("newhost:" + " " + UriValidator.IsUriValid("newhost:")); 
Console.WriteLine("qwerty:newhost" + " " + UriValidator.IsUriValid("qwerty:newhost")); 
Console.WriteLine("qwerty://newhost" + " " + UriValidator.IsUriValid("qwerty://newhost")); 
Console.WriteLine("qwerty://newhost:800" + " " + UriValidator.IsUriValid("qwerty://newhost:800")); 
Console.WriteLine("http://newhost/path/to/service" + " " + UriValidator.IsUriValid("http://newhost/path/to/service")); 

它給了以下的輸出:

https://newhost/
http://newhost:800
newhost:800假
newhost:Fal SE
QWERTY:newhost假
QWERTY:// newhost真
QWERTY:// newhost:800真
http://newhost/path/to/service

這似乎是你以後在做什麼!

注意的URI像qwerty://newhost仍然驗證爲True的QWERTY 可能您的系統上註冊的有效協議。如果您只想要允許http和/或https,那麼添加此項應該是微不足道的。