- Hands-On Full:Stack Web Development with ASP.NET Core
- Tamir Dresher Amir Zuker Shay Friedman
- 275字
- 2021-06-10 19:37:27
Creating a simple API
The GiveNTake application allows the user to see a catalog of available products. For this to be possible, our server needs to include a specific API method that the client application can call and get back the collection of available products.
We will define the structure of the product entity in Chapter 5, Persisting Data with Entity Framework. For now, we will treat the product as a simple string in the format of [Product ID] - [Product Name]:
- Open the GiveNTake project you created in Chapter 3, Creating a Web Application with ASP.NET Core, and add a new controller class to the Controllers folder. Right-click on the newly created Controllers folder and choose Add | Controller.
- In the list of available templates, choose API Controller - Empty and click Add:
- Set the name to ProductsController and click Add.
- Add the following method to the generated controller:
public string[] GetProducts()
{
return new[]
{
"1 - Microwave",
"2 - Washing Machine",
"3 - Mirror"
};
}
- Your controller should look like this:
[Route("api/Products")]
[ApiController]
public class ProductsController : Controller
{
public string[] GetProducts()
{
return new[]
{
"1 - Microwave",
"2 - Washing Machine",
"3 - Mirror"
};
}
}
Congratulations! You have completed coding your first API method. The GetProducts method returns the collection of the available products.
To see it in action, build and run your project. This will open a browser with the base address of your ASP.NET application. Add the /api/Products string to the base address in the browser's address bar and execute it. You should see the collection of strings appear on the screen like so:

- Application Development with Qt Creator(Second Edition)
- 物聯網智慧安監技術
- Building E-commerce Sites with VirtueMart Cookbook
- 網管員典藏書架:網絡管理與運維實戰寶典
- 物聯網信息安全
- SD-WAN架構與技術(第2版)
- 世界互聯網發展報告·2019
- 網絡環境中基于用戶視角的信息質量評價研究
- 搶占下一個智能風口:移動物聯網
- TD-LTE無線網絡規劃與設計
- 4G小基站系統原理、組網及應用
- 網管第一課:網絡操作系統與配置管理
- AIoT應用開發與實踐
- TCP/IP基礎(第2版)
- Selenium WebDriver 3 Practical Guide