2010-01-15 86 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,那么添加此项应该是微不足道的。