11

我正在为 Netflix API 编写一个 .NET 包装器 API。

此时我可以选择将 URL 表示为字符串或 URI 对象。在我看来,两者都有很好的案例。

因此,如果您使用的是 API,您更喜欢哪一个?

4

3 回答 3

17

以下引用来自:框架设计指南
强烈推荐这本书给任何在 .Net 上开发框架的人

请务必使用System.Uri 来表示 URI / URL 数据。
(对于参数、属性和返回值)

System.Uri 是一种更安全、更丰富的 URI 表示方式。使用纯字符串对 URI 相关数据的广泛操作已被证明会导致许多安全性和正确性问题。

考虑使用 System.Uri 参数为最常用的成员提供基于字符串的重载。

如果从用户那里获取字符串的使用模式足够普遍,您应该考虑添加一个接受字符串的便利重载。基于字符串的重载应该按照基于 Uri 的重载来实现。

不要使用接受字符串的版本自动重载所有基于 Uri 的成员。

通常,首选基于 Uri 的 API。基于字符串的重载旨在为最常见的场景提供帮助。因此,您不应自动为基于 Uri 的成员的所有变体提供基于字符串的重载。有选择性,只为最常用的变体提供此类帮助程序。

编辑(根据评论):该书特别指出:“使用纯字符串对 URI 相关数据的广泛操作已被证明会导致许多安全性和正确性问题。” 我不确定使用 System.Uri / UriBuilder 需要什么额外的理由。此外,您为什么不想利用框架来读取/操作 URI?

在设计将被其他人使用的 API 时,重要的是要使它们易于使用且可靠。出于这个原因,本书确实提到,您应该为常见功能提供“不错的”重载。但是,为了确保正确性,您应该始终使用 URI 实现底层代码。

您能否阐明您的需求或仅使用字符串的原因?

于 2008-10-18T08:36:19.310 回答
1

I would say that you should represent it as URI. However, if I am a user of your API and I am having to continuously convert string based URLs to URI to use your API, then I would be a pissed off user.

What I am saying is that you need to assess what kind of audience will be consuming your API.

于 2008-10-18T09:05:41.140 回答
0

One thing I found was that while writing string-accepting methods, I'd always have to initialize a Uri object anyway just to validate the string, such that the UriFormatException would then propagate out of the method if the user passed a bad string. But if you accept Uris only, as I did after getting yelled at (rightfully) by FxCop, then you always know your input is valid---which to me seems like a very good sign that you're designing your API correctly.

于 2008-10-18T09:13:21.000 回答