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

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:

主站蜘蛛池模板: 枞阳县| 谷城县| 本溪| 青海省| 两当县| 依兰县| 寿阳县| 沽源县| 霍林郭勒市| 尉犁县| 长宁区| 鸡泽县| 姚安县| 苍山县| 凉城县| 庆城县| 平阳县| 克拉玛依市| 措美县| 桐城市| 虞城县| 公安县| 曲麻莱县| 仪征市| 颍上县| 界首市| 新乡市| 禄劝| 漳平市| 泊头市| 阳城县| 固始县| 合肥市| 太谷县| 怀远县| 晋州市| 榆中县| 永昌县| 喜德县| 长子县| 垫江县|