我对ServiceStack很新,我试图找出在同一个请求上处理多个get操作的最佳实践。以下是我的请求对象:
[Route("/Entity", Verbs = "GET", Notes = "Returns all the entities.")]
[Route("/Entity/{Id}", Verbs = "GET", Notes = "Returns a specific entity.")]
[Route("/Entity/{Id}/Child", Verbs = "GET", Notes = "Returns children of a specific entity.")]
public class EntityRequest {
public int Id { get; set; }
public int ChildId { get; set; }
}
以下是我的服务:
public object Get(EntityRequest request) {
if (request.Id > 0) {
//returns a given entity
return _applicationService.getEntities(request.Id);
}
//How do I handle this? Check for the word "/Child" in the URL?
//returns children for a given entity
//return _applicationService.getChildren(request.Id);
//returns all the entities
return _applicationService.getEntities();
}
}
正如您所看到的,我正在处理前两条路线" /实体"和" /实体/ {Id}"从服务方面来说。我怎样才能最好地处理" / Entity / {Id} / Child"路线?在当前状态下,第三个URL将返回所有实体。任何帮助将不胜感激?
谢谢!
答案 0 :(得分:4)
请看下面这些现有的答案,这些答案通过推荐的方式来设计ServiceStack服务:
如果响应不同,建议使用不同的服务。您的服务也应该是自我描述的,而不是依赖于Notes中的文档来描述每个服务(很少有人阅读),所以我会将您的服务重新设计为:
[Route("/entities")]
public class GetAllEntities : IReturn<GetAllEntitiesResponse> {}
public class GetAllEntitiesResponse
{
public List<Entity> Results { get; set; }
}
如果您还希望您的服务能够提供查询实体的功能,请查看AutoQuery,它允许您使用下面的请求DTO创建完全可查询的RDBMS支持的服务:
[Route("/entities/search")]
public class QueryEntities : QueryBase<Entity> {}
其余服务类似于针对每种不同类型服务的单独请求DTO,其中请求DTO将包含调用该服务所需的所有属性,例如:
[Route("/entities/{Id}")]
public class GetEntity : IReturn<GetEntityResponse>
{
public int Id { get; set; }
}
public class GetEntityResponse
{
public Entity Result { get; set; }
}
同样适用于儿童实体服务:
[Route("/entities/{Id}/children")]
public class GetEntityChildren : IReturn<GetEntityChildrenResponse>
{
public int Id { get; set; }
}
public class GetEntityChildrenResponse
{
public List<EntityChild> Results { get; set; }
}
以这种方式设计您的服务可以明确每个服务的功能,每个服务所期望的参数以及它返回的内容。使用ServiceStack's Typed Service Clients调用上述服务时也会反映出来,例如:
var response = client.Get(new GetAllEntities());
var response = client.Get(new GetEntity { Id = 1 });
var response = client.Get(new GetEntityChildren { Id = 1 });
我个人的偏好是为每个服务使用明确的响应DTO,因为它将来证明服务,并允许您稍后进化服务以在不破坏现有服务客户端的情况下返回其他结果,但如果您愿意,您可以改为返回结果直接没有明确的Response DTO包装器,例如:
[Route("/entities")]
public class GetAllEntities : IReturn<List<Entity>> {}
[Route("/entities/{Id}")]
public class GetEntity : IReturn<Entity>
{
public int Id { get; set; }
}
[Route("/entities/{Id}/children")]
public class GetEntityChildren : IReturn<List<EntityChild>>
{
public int Id { get; set; }
}