我无法想象如果您有一个具有 4+ 方法的服务,那么您真的需要创建 4+ 服务类、4+ 请求 DTO 和 4+ 响应 DTO。
不,您需要 1 个具有 4 种方法的服务类 - 每个方法当然需要一个请求 Dto 并返回一个响应 Dto。显然,对于某些方法,您可能不需要响应 Dto
例如,具有 5 种方法的典型服务可能如下所示:
public class ProductsService: Service
{
[Route("/products")]
public class GetProductsRequest: IReturn<List<ProductResponse>> {}
public class ProductResponse
{
public int Id { get; set; }
public string Name { get; set; }
}
public object Get(GetProductsRequest request)
{
IEnumerable<ProductResponse> response = ...
return response;
}
[Route("/products/{id}")]
public class GetProductRequest: IReturn<ProductResponse>
{
public int Id { get; set; }
}
public object Get(GetProductRequest request)
{
ProductResponse response = ...
return response;
}
[Route("/products")]
public class CreateProductRequest
{
public string Name { get; set; }
}
public object Put(CreateProductRequest request)
{
... create the product here
return new HttpResult { StatusCode = HttpStatusCode.Created };
}
[Route("/products/{id}")]
public class UpdateProductRequest
{
public int Id { get; set; }
public string Name { get; set; }
}
public object Patch(UpdateProductRequest request)
{
... update the product here
return new HttpResult { StatusCode = HttpStatusCode.Accepted };
}
[Route("/products/{id}")]
public class DeleteProductRequest
{
public int Id { get; set; }
}
public object Delete(DeleteProductRequest request)
{
... delete the product here
return new HttpResult { StatusCode = HttpStatusCode.Accepted };
}
}
我已将请求和响应 DTO 作为嵌套类放入服务中,但将它们放在单独的文件中会更易读:
public class ProductsService: Service
{
public object Get(GetProductsRequest request)
{
IEnumerable<ProductResponse> response = ...
return response;
}
public object Get(GetProductRequest request)
{
ProductResponse response = ...
return response;
}
public object Put(CreateProductRequest request)
{
... create the product here
return new HttpResult { StatusCode = HttpStatusCode.Created };
}
public object Patch(UpdateProductRequest request)
{
... update the product here
return new HttpResult { StatusCode = HttpStatusCode.Accepted };
}
public object Delete(DeleteProductRequest request)
{
... delete the product here
return new HttpResult { StatusCode = HttpStatusCode.Accepted };
}
}