建立一個Controllers目錄, 然後建立一個“控制器類” ProductController.cs, 它需要繼承Microsoft.AspNetCore.Mvc.Controller
在Controller裏面寫這個Get方法:
namespace CoreBackend.Api.Controllers
{
public class ProductController: Controller
{
public JsonResult GetProducts()
{
return new JsonResult(new List<Product>
{
new Product
{
Id = 1,
Name = "牛奶",
Price = 2.5f
},
new Product
{
Id = 2,
Name = "麪包",
Price = 4.5f
}
});
}
}
}
然後運行, 並使用postman來進行請求:
請求的網址返回404 Not Found, 因爲還沒有配置路由 Routing, 所以MVC不知道如何處理/映射這些URI。