建立一個Services目錄, 然後建立一個 ProductService.cs類
我們把獲取數據的代碼整理成一個ProductService, 然後保證程序運行的時候, 操作的是同一批數據:
namespace CoreBackend.Api.Services
{
public class ProductService
{
public static ProductService Current { get; } = new ProductService();
public List<Product> Products { get; }
private ProductService()
{
Products = new List<Product>
{
new Product
{
Id = 1,
Name = "牛奶",
Price = 2.5f
},
new Product
{
Id = 2,
Name = "麪包",
Price = 4.5f
},
new Product
{
Id = 3,
Name = "啤酒",
Price = 7.5f
}
};
}
}
}
然後修改一下ProductController.cs裏面的代碼:
namespace CoreBackend.Api.Controllers
{
[Route("api/[controller]")]
public class ProductController: Controller
{
[HttpGet]
public JsonResult GetProducts()
{
return new JsonResult(ProductService.Current.Products);
}
}
}
也是同樣的運行效果.