asp.net web api 开发时应当注意的事项
- Self referencing when returning chain of objects. This can be solved using a design pattern called theModel Factory.
- We are returning all the fields from the domain model object and leaking sensitive information to the client, for example if you take a look on “Tutor” object you will notice that we are returning the “password” field which shouldn’t be leaked to API consumer. This can be solved using the Model Factory pattern.
- Each resource returned in the response should be linked to a URI, this will simplify resources query for the client. This can be solved using the Model Factory pattern.
- We should return HTTP status code when returning single resource, i.e if the resource was not found we should return 404 in response header, if it was found we should return 200 OK, etc…, this can be solved by returning HttpResponseMessage object.
- Inside each method we are instantiating our repository, this operation is expensive as it includes opening connection to the database, we need to implement Dependency Injection pattern, this can be solved by using Ninject DI framework.
- The format for JSON response objects are in Pascal Case i.e. “FirstName”, and most probably our API will be consumed in client using JavaScript, it is easier for JS developers to work with properties formatted in Camel Case “firstName”. this can be solved by configuring JSON formatters of the response.
返回对象时出现循环依赖,可以通过模型工厂模式解决。
我们返回了领域模型中所有的字段给客户端,然而有一些敏感信息不应该返回(例如:password字段),解决方案:模型工厂模式
每一个返回给客户端的资源都应该包含一个URI以便客户端查询,解决方案依旧是模型工厂模式。
对于返回单个资源,我们应当返回相应的状态码(例如:成功200,资源未找到404等),解决方案:HttpResponseMessage对象
在每个方法里我们都实例化了一个repository,这个对象包含了一些昂贵的操作(例如:数据库连接),解决方案:依赖注入模式
对于返回的Json对象格式是以“帕斯卡”风格的(例如“FirstName”),然而我们的Api有很大的可能被带有Javascript的客户端消费,对于JS开发者来说可能更适合“驼峰”风格(例如”firstName”)的数据。解决方案:配置Json格式。