【问题标题】:Net Core: Create Response Class for Each API Action?Net Core:为每个 API 操作创建响应类?
【发布时间】:2019-09-23 14:49:45
【问题描述】:

我们的软件架构师要求所有 API 操作都有自己的响应类,因为每个响应都可能略有不同。因此,我们基本上将 Product DTO 包装在 Base Response 类中,并在需要时稍微定制。这是良好的架构实践吗?我开始编程,它似乎有点重复。另外,什么是更好的最佳选择?

产品类别:

public class ProductDto
{
    public int ProductId { get; set;},
    public string ProductName { get; set;},
    public string ProductDescription { get; set;},
    public float SalesAmount { get; set;}
}

基本响应:

public class BaseResponse<T>
{
    [Required, ValidateObject]
    public T Body { get; set; }
    public bool HasError { get; set; }
    public string Error { get; set; }
}

个人回复:

public class CreateProductResponse : BaseResponse<ProductDto>
{
}

public class DeleteProductResponse : BaseResponse<int>
{
}

public class GetAllProductResponse : BaseResponse<IEnumerable<ProductDto>>
{
    public int Count { get; set;};
}

public class GetProductResponse : BaseResponse<ProductDto>
{
}

public class UpdateProductResponse : BaseResponse<ProductDto>
{
    public date DateUpdate { get; set;}
}

【问题讨论】:

  • 主要开发者的任务是让一个复杂的问题变得简单易懂,如果代码中的重复有助于它,我相信它还不错。在您提到的情况下,我认为这不是重复,而是inheritanceGeneric type,这是可以接受的。
  • 您(和架构师)可能对 GraphQL 感兴趣,而不是构建自己的协议。
  • 嗨@huysentruitw 我读到了有关graphql的信息,这在什么意义上会有所帮助?仍然需要为响应类型创建不同的模型,有什么推荐的解决方案,请随时回答,谢谢-
  • 是的,您将需要不同的模型,但您不再需要将它们包装在泛型中。

标签: c# .net asp.net-core .net-core request-response


【解决方案1】:

至少对于当前的示例,我会说这有点多虑了。 有许多派生类没有其他自己的属性。可能在未来,同样的模式将继续存在。

更好的解决方案是将 BaseResponse 作为一个接口,以获得更好的可扩展性,以实现多个不同接口的相同属性。 下面是更详细的信息。

https://softwareengineering.stackexchange.com/questions/382882/why-inherit-a-class-and-not-add-properties

【讨论】:

    【解决方案2】:

    通过查看这段代码很难说架构实践的好坏。在我们的例子中,我们使用下面的模式并认为它是合理的

    public class BaseResponse
    {
        public bool HasError { get; set; }
        public string Error { get; set; }
    }   
    
    
    public class CreateProductResponse : BaseResponse
    {
     ---
    }
    
    public class CreateProductDetailResponse : CreateProductResponse
    {
     ---
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-25
      • 1970-01-01
      • 2021-06-02
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 2012-04-01
      • 2019-10-09
      相关资源
      最近更新 更多