0

I'm working on a C# project where I need to combine a base URL with various endpoints. However, I'm running into issues when the endpoint has a leading slash. For example:

string baseUrl = "https://example.com/api/v1/"; string endpoint = "/sessions/logon/"; Uri baseUri = new Uri(baseUrl); Uri fullUri = new Uri(baseUri, endpoint); Console.WriteLine(fullUri); 

This code results in https://example.com/sessions/logon instead of the expected https://example.com/api/v1/sessions/logon. The leading slash in the endpoint causes it to override the base URL path.

Is there a robust way to combine URIs that correctly handles leading/trailing slashes?

1
  • Is there a robust way to combine URIs that correctly handles leading/trailing slashes? yes - use a library that does all that plus handles all the edge cases you haven’t thought of - eg flurl.dev Commented Jun 20, 2024 at 11:45

1 Answer 1

0

I came up with a solution that involves creating an extension method to handle this scenario. Here’s the extension method I developed:

public static class UriExtension { public static Uri Combine(this Uri baseUri, params string[] endpoints) { // Convert baseUri to string, trim it, and ensure it ends with a slash string baseUrl = baseUri.ToString().TrimEnd('/') + "/"; // Trim each endpoint and join them with slashes string combinedPath = string.Join("/", endpoints.Select(e => e.Trim('/'))); Uri fullUri = new Uri(new Uri(baseUrl), combinedPath); return fullUri; } } 

Usage

Here's how I use this extension method in my code. I've split the endpoint into parts just to illustrate the issue with the slashes:

Uri baseUri = new Uri("https://example.com/api/v1/"); string[] endpoints = { "/sessions/", "/logon/" }; Uri fullUri = baseUri.Combine(endpoints); Console.WriteLine(fullUri); 

This method ensures that no matter if the URIs have slashes at the beginning or end, they will be correctly combined into https://example.com/api/v1/sessions/logon/.

This solution has worked well for me, handling all variations of leading and trailing slashes gracefully.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.