2013-04-17 109 views
2

我开始尝试使用ServiceStack,到目前为止我都很喜欢它,但我认为我的设计有缺陷。基本上,我有一个MSSQL数据库,我通过NHibernate访问。由于我的请求/响应DTOs &服务应该采用什么结构,我的困惑正在出现。ServiceStack REST API设计

我有一个单独的项目我的NHibernate的映射下MyProject.Common.Models其中包含了“客户”类像这样:

namespace MyProject.Common.Models 
{ 
    public class Client 
    { 
     public virtual int ClientID { get; set; } 
     public virtual string Name { get; set; } 
     public virtual string Acronym { get; set; } 
     public virtual string Website { get; set; } 
    } 

    public class ClientMap : ClassMap<Client> 
    { 
     public ClientMap() 
     { 
      Id(x => x.ClientID, "ClientID").GeneratedBy.Identity(); 

      Map(x => x.Name, "Name"); 
      Map(x => x.Acronym, "Acronym"); 
      Map(x => x.Website, "Website"); 
     } 
    } 
} 

我想提供客户端CRUD单个客户端的能力,以及显示所有客户的列表。到目前为止,我设计我的一个客户端的请求,像这样:

[Route("/clients/{Id}", "GET")] 
public class ClientRequest : IReturn<ClientResponse> 
{ 
    public string Id { get; set; } 
} 

public class ClientResponse : IHasResponseStatus 
{ 
    public MyProject.Common.Models.Client Client { get; set; } 
    public ResponseStatus ResponseStatus { get; set; } 

    public ClientResponse() 
    { 
     this.ResponseStatus = new ResponseStatus(); 
    } 
} 

正如你所看到的只是我的模型类返回给客户端。通过这种设计,我完全不知道如何正确发布新客户端或更新现有客户端。另外,如果我想回到所有客户的名单,我目前使用下面的请求/响应的DTO:

[Route("/clients", "GET")] 
public class ClientsRequest : IReturn<ClientsResponse> 
{ 

} 
public class ClientsResponse : IHasResponseStatus 
{ 
    public List<MyProject.Common.Models.Client> Clients { get; set; } 
    public ResponseStatus ResponseStatus { get; set; } 

    public ClientsResponse() 
    { 
     this.ResponseStatus = new ResponseStatus(); 
    } 
} 

与服务,像这样:

public ClientsResponse Get(ClientsRequest request) 
{ 
    var result = currentSession.Query<Chronologic.Eve.Common.Models.Client>().ToList(); 

    if (result == null) 
     throw new HttpError(HttpStatusCode.NotFound, new ArgumentException("No clients exist")); 

    return new ClientsResponse 
    { 
     Clients = result 
    }; 
} 

其中一期工程,虽然我觉得这样也没有达到我所试图做的最好的办法,并给了我一个丑陋的元数据页面显示如下所示:

Ugly ServiceStack metadata

我觉得我忽略了这个设计很简单,如果有人可以告诉我如何简化设计,将不胜感激。

谢谢。

回答

6

你应该看看这些早期的帖子,这将有助于与API设计ServiceStack:

而不是重新哈希任何内容包含上面,我会重写它,我会怎么做。

您不需要ResponseStatus属性,以便您的服务可以返回干净的DTO。

[Route("/clients", "GET")] 
public class AllClients : IReturn<List<Client>> {} 

[Route("/clients/{Id}", "GET")] 
public class GetClient : IReturn<Client> 
{ 
    public string Id { get; set; } 
} 

基于上述请求DTO,服务实现应该是直截了当的。

通过上述API,您的C#客户端调用的地方现在看起来像:

List<Client> clients = service.Get(new AllClients()); 

Client client = service.Get(new GetClient { Id = id }); 
+0

非常感谢杰米斯!自从去年初我在上次玩SS时,我觉得这是完全不同的方式。 – slashp

+0

是的,[新的API](https://github.com/ServiceStack/ServiceStack/wiki/New-Api)允许更多的自由,这总是很好:) – mythz