You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中可靠合并URI,正确处理首尾斜杠?

解决C#中基础URL与端点合并时的斜杠问题

你遇到的问题是Uri类的标准行为:当传入的端点以/开头时,会被视为绝对路径引用,根据RFC 3986的规则,它会直接替换基础URI的整个路径部分,而非追加到现有路径后。

以下是几种可靠的解决方法:

方法1:手动标准化端点格式

直接移除端点的前导斜杠,确保它是相对路径:

string baseUrl = "https://example.com/api/v1/";
string endpoint = "/sessions/logon/";

// 移除端点的前导斜杠
endpoint = endpoint.TrimStart('/');
Uri fullUri = new Uri(new Uri(baseUrl), endpoint);

Console.WriteLine(fullUri); // 输出: https://example.com/api/v1/sessions/logon/

方法2:使用UriBuilder合并路径

提取基础URI的路径,结合端点路径进行合并后重新构建URI:

string baseUrl = "https://example.com/api/v1/";
string endpoint = "/sessions/logon/";

Uri baseUri = new Uri(baseUrl);
// 合并路径:先清理首尾斜杠,再用Path.Combine拼接
string combinedPath = Path.Combine(
    baseUri.AbsolutePath.TrimEnd('/'),
    endpoint.TrimStart('/')
);

UriBuilder builder = new UriBuilder(baseUri);
builder.Path = combinedPath;
Uri fullUri = builder.Uri;

Console.WriteLine(fullUri); // 输出: https://example.com/api/v1/sessions/logon

方法3:封装通用合并方法

写一个可复用的辅助方法,自动处理首尾斜杠的问题:

public static Uri CombineUri(string baseUrl, string endpoint)
{
    if (string.IsNullOrWhiteSpace(baseUrl))
        throw new ArgumentNullException(nameof(baseUrl));
    if (string.IsNullOrWhiteSpace(endpoint))
        return new Uri(baseUrl);

    // 确保基础URL末尾有且仅有一个斜杠
    string normalizedBase = baseUrl.EndsWith('/') ? baseUrl : baseUrl + '/';
    // 移除端点的所有前导斜杠
    string normalizedEndpoint = endpoint.TrimStart('/');

    return new Uri(new Uri(normalizedBase), normalizedEndpoint);
}

// 使用示例
string baseUrl = "https://example.com/api/v1/";
string endpoint = "/sessions/logon/";
Uri fullUri = CombineUri(baseUrl, endpoint);

Console.WriteLine(fullUri); // 输出: https://example.com/api/v1/sessions/logon/

这些方法都能确保无论基础URL是否带末尾斜杠、端点是否带前导斜杠,都能正确合并出预期的完整URI。

内容的提问来源于stack exchange,提问作者Alex Hovy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:35:05