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
Release: 2025-01-09 14:02:41
Original
1054 people have browsed it

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:

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;
Copy after login

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:

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
Copy after login

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template