- 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:

- 社交網(wǎng)絡(luò)對(duì)齊
- C++黑客編程揭秘與防范
- 物聯(lián)網(wǎng)之魂:物聯(lián)網(wǎng)協(xié)議與物聯(lián)網(wǎng)操作系統(tǒng)
- 異構(gòu)基因共表達(dá)網(wǎng)絡(luò)的分析方法
- OpenLayers Cookbook
- 萬(wàn)物互聯(lián):蜂窩物聯(lián)網(wǎng)組網(wǎng)技術(shù)詳解
- 局域網(wǎng)組建、管理與維護(hù)項(xiàng)目教程(Windows Server 2003)
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- C/C++串口通信:典型應(yīng)用實(shí)例編程實(shí)踐
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- 5G+區(qū)塊鏈
- 物聯(lián)網(wǎng)基礎(chǔ)及應(yīng)用
- 路由與交換技術(shù)
- 目標(biāo)跟蹤中的群智能優(yōu)化方法
- Oracle ADF Faces Cookbook