官术网_书友最值得收藏!

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

  1. 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.
  2. In the list of available templates, choose API Controller - Empty and click Add:

  1. Set the name to ProductsController and click Add.
  2. Add the following method to the generated controller:
public string[] GetProducts()
{
return new[]
{
"1 - Microwave",
"2 - Washing Machine",
"3 - Mirror"
};
}
  1. 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:

主站蜘蛛池模板: 安多县| 红原县| 祁门县| 灵台县| 赤水市| 九江市| 双江| 勐海县| 辉县市| 舟山市| 常宁市| 达州市| 麦盖提县| 建始县| 深水埗区| 海口市| 夏河县| 文登市| 惠东县| 盐池县| 绥滨县| 清水河县| 安乡县| 玉门市| 汽车| 新民市| 永兴县| 五莲县| 龙陵县| 永宁县| 大兴区| 宜兰市| 梓潼县| 冕宁县| 加查县| 平度市| 金溪县| 莱州市| 松桃| 噶尔县| 宁化县|