有没有更好的方法来验证C#字符串是否是有效的xs:anyURI而不是以下? public bool VerifyAnyURI(string anyUriValue){ bool result = false; try { SoapAnyUri anyUri = new SoapAnyUri(anyUriValue); result = true; } catch (Ex
public bool VerifyAnyURI(string anyUriValue) { bool result = false; try { SoapAnyUri anyUri = new SoapAnyUri(anyUriValue); result = true; } catch (Exception) { } return result; }
此构造函数似乎不会抛出任何类型的异常.从技术上讲,任何有效字符串都是有效的anyURI吗?
使用Reflector查看SoapAnyUri构造函数,它根本不执行任何验证.anyURI数据类型is defined as follows:
[Definition:] anyURI represents a Uniform Resource Identifier Reference (URI). An anyURI value can be absolute or relative, and may have an optional fragment identifier (i.e., it may be a URI Reference). This type should be used to specify the intention that the value fulfills the role of a URI as defined by [RFC 2396], as amended by [RFC 2732].
因此,您只需使用Uri.TryCreate
和UriKind.RelativeOrAbsolute来验证字符串是否代表有效值:
Uri uri; bool valid = Uri.TryCreate(anyUriValue, UriKind.RelativeOrAbsolute, out uri);