Validating HTTP (and HTTPS) URLs in C#
During the input validation process, it is crucial to verify the validity of the HTTP URL. However, built-in methods such as Uri.IsWellFormedUriString
and Uri.TryCreate
may recognize non-HTTP file paths as valid URLs.
Solution:
To specifically check HTTP URLs, use the following code:
Uri uriResult; bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
This code checks whether the string uriName
can be resolved to an absolute URI and ensures that its scheme is specifically "http".
Expands to HTTP and HTTPS:
If the validation should contain both HTTP and HTTPS URLs, please modify the code as follows:
Uri uriResult; bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
The above is the detailed content of How Can I Validate HTTP (and HTTPS) URLs in C#?. For more information, please follow other related articles on the PHP Chinese website!