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

C#实现移除URI末尾斜杠并保留查询参数

在C#中移除URI末尾斜杠并保留查询参数

要实现移除URI末尾斜杠同时保留查询参数的需求,推荐利用Uri类的内置属性拆分重组URI,这种方式能自动处理编码、端口、权限部分等细节,比手动字符串操作更可靠。以下是两种实用方案:

方案一:扩展方法(推荐)

编写Uri的扩展方法,复用性强,能覆盖所有合法URI场景:

public static class UriExtensions
{
    public static Uri RemoveTrailingSlash(this Uri uri)
    {
        if (uri == null)
            throw new ArgumentNullException(nameof(uri));

        // 处理路径:移除末尾斜杠,根路径"/"保留
        string processedPath = uri.AbsolutePath.TrimEnd('/');
        processedPath = string.IsNullOrEmpty(processedPath) ? "/" : processedPath;

        // 拼接所有URI组件
        string newUri = string.Concat(
            uri.Scheme,
            "://",
            uri.Authority,
            processedPath,
            uri.Query
        );

        return new Uri(newUri);
    }
}

使用示例

// 无查询参数的URI
Uri originalUri1 = new Uri("https://stackoverflow.com/questions/ask/");
Uri cleanedUri1 = originalUri1.RemoveTrailingSlash();
// 输出:https://stackoverflow.com/questions/ask

// 带查询参数的URI
Uri originalUri2 = new Uri("https://stackoverflow.com/questions/ask/?test=test1&foo=bar");
Uri cleanedUri2 = originalUri2.RemoveTrailingSlash();
// 输出:https://stackoverflow.com/questions/ask?test=test1&foo=bar

// 根路径URI
Uri originalUri3 = new Uri("https://example.com/");
Uri cleanedUri3 = originalUri3.RemoveTrailingSlash();
// 输出:https://example.com/

方案二:字符串直接处理(简单场景)

如果只处理已知结构的简单URI,可以直接拆分路径和查询参数部分,但需兼容根路径、带端口的URI等情况:

public static Uri RemoveTrailingSlashFromString(string uriString)
{
    if (string.IsNullOrWhiteSpace(uriString))
        throw new ArgumentException("URI字符串不能为空", nameof(uriString));

    int queryStartIndex = uriString.IndexOf('?');
    string pathSegment = queryStartIndex == -1 ? uriString : uriString[..queryStartIndex];
    string querySegment = queryStartIndex == -1 ? string.Empty : uriString[queryStartIndex..];

    // 移除路径末尾斜杠,避免出现"https://example.com"这种无路径的情况
    pathSegment = pathSegment.TrimEnd('/');
    if (pathSegment.EndsWith("://"))
        pathSegment += "/";

    return new Uri(pathSegment + querySegment);
}

注意事项

  • 优先选择方案一:Uri类会自动处理URI的编码、特殊字符、端口号(如https://example.com:8080/)等复杂情况,避免手动字符串操作的潜在bug。
  • 根路径处理:两种方案都会保留根路径的/,符合常见的URI规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:35:19