Robust Input Validation: Verifying HTTP and HTTPS URLs in C#
Secure input validation is crucial for any application. Simply checking if a string looks like a URL isn't sufficient; we need to ensure it's a valid HTTP or HTTPS address. Methods like Uri.IsWellFormedUriString
can be misleading, accepting file paths as valid URLs.
A More Precise Solution
This improved approach accurately validates HTTP and HTTPS URLs, preventing vulnerabilities:
<code class="language-csharp">Uri uriResult; bool isValid = Uri.TryCreate(uriString, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);</code>
This code uses Uri.TryCreate
to attempt parsing the input string (uriString
). UriKind.Absolute
ensures only absolute URLs are accepted. The subsequent check verifies the scheme is either http
or https
, guaranteeing a valid web address. The result (isValid
) is a boolean indicating whether the input is a valid HTTP or HTTPS URL.
This method provides a more reliable and secure way to validate URLs in C#, effectively preventing the acceptance of potentially harmful inputs.
The above is the detailed content of How Can I Reliably Validate HTTP and HTTPS URLs in C#?. For more information, please follow other related articles on the PHP Chinese website!