How to Syntactically Validate a URL in C# .NET Framework
1 min readJul 14, 2020
If you need a quick validation solution for URLs, then checking syntax is a great way to go about it. While lacking the power of full validation, this method can be great when handling trusted URLs. So should we start by laying out a model for URL structure and going over all the variations and how to parse them? That would take forever! So instead, we will be making use of an API that can take care of this for us.
First we grab the package we need with NuGet:
Install-Package Cloudmersive.APIClient.NET.Validate -Version 3.0.6
Next we shall call the URL validation function from that library, like so:
using System;using System.Diagnostics;using Cloudmersive.APIClient.NET.Validate.Api;using Cloudmersive.APIClient.NET.Validate.Client;using Cloudmersive.APIClient.NET.Validate.Model;namespace Example{public class DomainUrlSyntaxOnlyExample{public void main(){// Configure API key authorization: ApikeyConfiguration.Default.AddApiKey("Apikey", "YOUR_API_KEY");// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new DomainApi();var request = new ValidateUrlRequestSyntaxOnly(); // ValidateUrlRequestSyntaxOnly | Input URL informationtry{// Validate a URL syntacticallyValidateUrlResponseSyntaxOnly result = apiInstance.DomainUrlSyntaxOnly(request);Debug.WriteLine(result);}catch (Exception e){Debug.Print("Exception when calling DomainApi.DomainUrlSyntaxOnly: " + e.Message );}}}}
Done! Talk about easy.