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
Release: 2025-01-09 13:46:40
Original
770 people have browsed it

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

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

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!

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