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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-09 13:46:40787browse

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

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!

Statement:
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