Reliable C# Validation for HTTP and HTTPS URLs
Standard C# URI validation methods like Uri.IsWellFormedUriString
and Uri.TryCreate
can sometimes misidentify file paths as URLs. This article demonstrates a more robust approach specifically designed for validating HTTP and HTTPS URLs.
Validating HTTP URLs:
The following C# code provides a precise method for HTTP URL validation:
<code class="language-csharp">Uri uriResult; bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;</code>
This efficiently checks if the input (uriName
) is a correctly formatted Uri
object and confirms that the scheme is "http".
Extending Validation to Include HTTPS:
To accept both HTTP and HTTPS URLs, simply modify the validation:
<code class="language-csharp">Uri uriResult; bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);</code>
This enhanced check accepts URLs with either "http" or "https" schemes.
Integrating this validation into your input processing ensures that only valid HTTP/HTTPS URLs are accepted, significantly improving the security and reliability of your application's input handling.
The above is the detailed content of How Can I Robustly Validate HTTP and HTTPS URLs in C#?. For more information, please follow other related articles on the PHP Chinese website!