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

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:

主站蜘蛛池模板: 绥滨县| 子长县| 科技| 蒙山县| 远安县| 永安市| 南康市| 安新县| 温宿县| 南丹县| 龙海市| 新巴尔虎左旗| 梁山县| 中卫市| 韩城市| 兴国县| 鹿邑县| 全州县| 中阳县| 南丹县| 阿克陶县| 江口县| 开平市| 尚义县| 淮安市| 邛崃市| 务川| 富裕县| 合江县| 永兴县| 新宾| 罗定市| 通河县| 深圳市| 阳朔县| 临湘市| 万盛区| 卓尼县| 五常市| 连南| 舒兰市|