Successfully added
.NET
by Patrik
Safely Combine URLs from Strings in .NET
Combining base URLs with relative paths in .NET can lead to errors if not handled carefully. This guide shows a safe and reusable way to do it using two methods: one that works with Uri
objects and another that accepts strings for convenience.
Why This Is Useful
- Prevents runtime errors from invalid or missing inputs
- Provides fallback behavior
- Easy to reuse in any .NET application
Implementation
Here's the core method that safely combines a Uri
with a relative path:
public static string SafeCombineUrl(Uri? baseUri, string relativePath)
{
try
{
if (string.IsNullOrWhiteSpace(relativePath))
{
return baseUri?.ToString() ?? string.Empty;
}
if (baseUri == null)
{
return relativePath;
}
return new Uri(baseUri, relativePath).ToString();
}
catch (Exception ex)
{
return $"[InvalidUrl={ex.Message}]";
}
}
To make it easier to use with strings, add this helper method:
public static string SafeCombineUrl(string baseUri, string relativePath)
{
try
{
Uri? baseUriObj = null;
if (!string.IsNullOrWhiteSpace(baseUri))
{
baseUriObj = new Uri(baseUri, UriKind.Absolute);
}
return SafeCombineUrl(baseUriObj, relativePath);
}
catch (Exception ex)
{
return $"[InvalidBaseUri={ex.Message}]";
}
}
How It Works
- If the
relativePath
is empty, it returns the base URL. - If the base is missing, it returns the relative path.
- If both are valid, it combines them.
- If there's an error, it returns a helpful message.
urls
uri
csharp
dotnet
helper-methods
Referenced in:
Comments