這邊可將DTO Model類別都移動至新增的Models目錄(自行額外新建)
用於將程式分門別類
~\Models\ProductModel.cs
namespace MyReact1.Models
{
public class ProductModel
{
public List<ProductListItem> Products { get; set; } = new List<ProductListItem>();
public class ProductListItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
}
~\Models\ProductDetailsModel.cs
namespace MyReact1.Models
{
public class ProductDetailsModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
抽離Model DTO後的
~\Controllers\ProductController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyReact1.Models;
namespace MyReact1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
public IActionResult List()
{
var model = new ProductModel
{
Products = new List<ProductModel.ProductListItem> {
new ProductModel.ProductListItem{Id = 1, Name = "The first", Description="product 1"}
}
};
return Ok(model);
}
// -> /api/Product/10
[HttpGet("{id}")]
public IActionResult Details(int id)
{
return Ok(new ProductDetailsModel
{
Id = id,
Name = "A product",
Description = "Description",
Price = 1000
});
}
}
}
可再另外擴增一個Services目錄
把業務邏輯額外封裝成一隻獨立職責的Service類別
~\Services\ProductService.cs
using MyReact1.Models;
namespace MyReact1.Services
{
public class ProductService
{
public static ProductModel GetProductList()
{
return new ProductModel
{
Products = new List<ProductModel.ProductListItem> {
new ProductModel.ProductListItem{Id = 1, Name = "The first", Description="product 1"}
}
};
}
public static ProductDetailsModel GetDetails(int id)
{
return new ProductDetailsModel
{
Id = id,
Name = "A product",
Description = "Description",
Price = 1000
};
}
}
}
最終再去重構ProductController.cs
把業務邏輯全部改為用Service做方法存取
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyReact1.Models;
using MyReact1.Services;
namespace MyReact1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
public IActionResult List()
{
ProductModel model = ProductService.GetProductList();
return Ok(model);
}
// -> /api/Product/10
[HttpGet("{id}")]
public IActionResult Details(int id)
{
return Ok(ProductService.GetDetails(id));
}
}
}