如何实现REST API嵌套URL的高效存储与点式访问?
实现嵌套URL结构的最佳方式
针对你需要的通过.运算符访问多层嵌套URL、运行时解析为完整字符串的需求,以下是几种最实用的实现方式,完全符合预期且比复杂自定义类更简便:
方案1:嵌套静态类+常量字符串
这是最直接的实现方式,适合URL结构固定、无需动态修改的场景,编译时就能检查错误,性能拉满:
public static class Url { public static class Things { public const string Search = "myurl.com/thethingsiwant/searchingthethings"; public const string Create = "myurl.com/thethingsiwant/creatingathing"; } // 可扩展其他层级分支 public static class User { public const string Profile = "myurl.com/user/profile"; public static class Settings { public const string Update = "myurl.com/user/settings/update"; } } }
使用方式:
myHttpClient.PostAsync(Url.Things.Search, mycontent); myHttpClient.PostAsync(Url.User.Settings.Update, mycontent);
方案2:嵌套静态类+属性拼接基础URL
如果需要区分测试/生产环境(基础URL可能变化),可以把基础URL抽离,通过属性动态拼接,避免重复修改每个URL:
public static class Url { // 基础URL可根据环境动态设置,比如从配置文件读取 private const string BaseUrl = "myurl.com"; public static class Things { private const string ThingsBase = $"{BaseUrl}/thethingsiwant"; public static string Search => $"{ThingsBase}/searchingthethings"; public static string Create => $"{ThingsBase}/creatingathing"; } public static class User { private const string UserBase = $"{BaseUrl}/user"; public static string Profile => $"{UserBase}/profile"; public static class Settings { private const string SettingsBase = $"{UserBase}/settings"; public static string Update => $"{SettingsBase}/update"; } } }
这种方式既保留了.运算符访问的便捷性,又解决了基础URL维护的问题,推荐大多数场景使用。
方案3:C# 9+ 嵌套记录类型
如果偏好更简洁的语法,可以用C# 9引入的记录类型实现嵌套,本质和静态类逻辑一致,但代码更紧凑:
public record Url { public static readonly ThingsRecord Things = new(); public static readonly UserRecord User = new(); public record ThingsRecord { public string Search => "myurl.com/thethingsiwant/searchingthethings"; public string Create => "myurl.com/thethingsiwant/creatingathing"; } public record UserRecord { public string Profile => "myurl.com/user/profile"; public SettingsRecord Settings => new(); public record SettingsRecord { public string Update => "myurl.com/user/settings/update"; } } }
使用方式和静态类完全一致:Url.Things.Create。
为什么字典/枚举不适合?
- 字典只能通过索引器(
url["things"]["search"])访问,无法实现.运算符调用,嵌套结构可读性差; - 枚举是平级结构,无法支持多层嵌套的分支URL,扩展性极差。
总结
最简便且符合需求的方式就是嵌套静态类,无论是常量还是属性拼接的形式,都能完美实现你要的多层级.访问、清晰的嵌套结构,且实现成本极低,无需引入额外框架或复杂逻辑。
内容的提问来源于stack exchange,提问作者Duncan Drust
相关产品推荐
相关产品推荐

