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

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:

主站蜘蛛池模板: 鲁甸县| 仙居县| 宁陕县| 南召县| 西盟| 马鞍山市| 富源县| 融水| 门头沟区| 吉首市| 三穗县| 车致| 武定县| 综艺| 商城县| 洛宁县| 沂源县| 于都县| 比如县| 潼南县| 鹿邑县| 宁陵县| 铜山县| 伊通| 黄梅县| 江永县| 灵璧县| 左云县| 蚌埠市| 桐乡市| 金平| 嘉峪关市| 色达县| 留坝县| 浦东新区| 江陵县| 盖州市| 开江县| 定远县| 华容县| 祥云县|