Home > Backend Development > C++ > How Can I Reliably Validate HTTP and HTTPS URLs in C#?

How Can I Reliably Validate HTTP and HTTPS URLs in C#?

Mary-Kate Olsen
Release: 2025-01-09 13:51:41
Original
415 people have browsed it

How Can I Reliably Validate HTTP and HTTPS URLs in C#?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template