Search code examples
c#.netasp.net-core.net-corerequest-response

Net Core: Create Response Class for Each API Action?


Our software architect is mandating all API Actions have their own Response Class, since every Response can be slightly difference. So we basically wrap the Product DTO in a Base Response class, and slightly customize if needed. Is this good architectural practice? I started programming and it Seems kind of repetitive. Also, what is a nicer optimal alternative for this?

Product Class:

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

BaseResponse:

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

Individual Response:

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;}
}

Solution

  • At least with a current example, I would say it's a bit overthinking. There are many derived classes who have no additional its own properties. Probably in the future, the same pattern will stay on.

    A better solution would be to make BaseResponse as an interface for better extensibility for implementing same properties of several different interfaces. Below it's more detailed information.

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