從零開始學習 asp.net core 2.1 web api 後端api基礎框架(六)-把獲取資料的程式碼整理成一個服務
阿新 • • 發佈:2018-11-06
建立一個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); } } }
也是同樣的執行效果.