使用 ConfigurationValidator 或其他验证器验证 Uri
在配置文件的自定义配置部分中,我希望属性或元素为服务端点定义新方案、主机和端口,但不定义路径。 因此,应该允许 https://newhost/
或 http://newhost:800
,但不允许 newhost:800
、http://newhost/path/to/service
。
实施的最佳选择是什么?
感觉应该有一个很好的 Uri.Parse、UriParser 重载,这会让事情变得容易。我是否错过了 UriValidator?或者正则表达式将是最好的选择(这样它就可以轻松地禁止该路径)?
请注意,这并不是特定于 ConfigurationValidator,因为可以重用的通用验证器会很有用。
In a custom configuration section of a config file I want to have properties or elements define a new scheme, host and port for a service endpoint, but not define the path.
So these should be allowed https://newhost/
or http://newhost:800
, but not newhost:800
, http://newhost/path/to/service
.
What would be the best option to implement?
It feels like there should be a good overload of a Uri.Parse, UriParser that would make it easy. Is there a UriValidator that I have missed? Or is regex going to be the best option (so that it can easily disallow the path)?
Note that this isn't specific to a ConfigurationValidator as a general validator that can be reused would be useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Uri
类的GetLeftPart
方法始终可以提供帮助。GetLeftPart 方法
GetLeftPart 方法从UriPartial 系统枚举,其中之一 (
UriPartial.Authority
)将返回:这有效地删除了原始字符串中可能存在的任何无关路径信息,并且如果提供的 Uri 不包含有效的 scheme (即 Uri 的 http 或 https 等部分)和/或权限(即在您的示例中,这是Uri 的
newhost
部分)。从这里开始,您应该能够将
GetLLeftPart
调用的返回值与原始 Uri 字符串进行比较,如果它们不同,则该 Uri 为“无效”。如果它们相同,则 Uri 是“有效的”(对于您的目的而言)。下面是一个简单的示例类,它将执行此“验证”,为 Uri 返回 True 或 False(C# 和 VB.NET 版本):
C#
VB.NET
我运行使用此类进行一个简单的测试:
它给出了以下输出:
这似乎就是您所追求的!
请注意,像
qwerty://newhost
这样的 Uri 仍然验证为True
,因为 qwerty可能 是在您的系统上注册的有效协议。如果您只想允许http
和/或https
,那么添加它应该很简单。There is always the
GetLeftPart
method of theUri
class that could help here.GetLeftPart Method
The GetLeftPart method takes an enumeration from the UriPartial system enumeration, one of which (
UriPartial.Authority
) will return:This effectively removes any extraneous path information that may be in the original string, and will usually return a zero-length string if the Uri supplied does not contain a valid scheme (i.e. the http or https etc. parts of the Uri) and/or authority (i.e. in your example, this is the
newhost
part of the Uri).From here, you should be able to compare the return value of the call to
GetLLeftPart
with the original Uri string, and if they're different, the Uri is "invalid". If they're the same, the Uri is "valid" (for your purposes).Here's a simple example class that will perform this "validation" returning either True or False for the Uri (both C# and VB.NET versions):
C#
VB.NET
I ran a simple test using this class:
And it gave the following output:
which seems to be what you're after!
Note that Uri's like
qwerty://newhost
still validate asTrue
as qwerty could be a valid protocol registered on your system. If you only wanted to allowhttp
and/orhttps
, it should be trivial to add this in.