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

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

DDD
DDDOriginal
2025-01-09 14:02:411080browse

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

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:

<code class="language-csharp">Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;</code>

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:

<code class="language-csharp">Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);</code>

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!

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