如何在.NET Core中创建API

tech2022-07-13  143

目录

实现目标

什么是API?

什么是JSON?

步骤1:运行Dotnet命令

步骤2:探索您的项目

步骤3:设定环境

步骤4:建立模型

步骤5:创建控制器

第6步:将Swagger添加到您的项目

步骤7:测试您的API

步骤8:验证结果

方法GetAll

方法Post


实现目标

我们有一家虚构的公司,需要提供一组方法来执行这些操作:

创建一个产品阅读产品更新产品删除产品

将使用这些API方法的外部应用程序具有如下屏幕:

在这种情况下,我们有一个具有4个字段的Product实体:

ProductintNamestringImageUrlstringPricedecimal

在开始编码之前,建议您重新了解有关APIJSON格式的基本概念。

什么是API

我已经阅读了很多有关此概念的定义,并且我更希望记住这一点:

API是一种软件如何与另一种软件交互的规范。

在我们的示例中,我们将创建一组片段(方法),这些片段将负责执行与外部应用程序交互的特定任务。

运作方式

Http动词

创建一个产品

POST

阅读产品

GET

更新产品

UPDATE

删除产品

DELETE

什么是JSON

JSON代表JavaScript对象符号JSON是用于存储和传输数据的轻量级格式数据从服务器发送到网页时,通常使用JSONJSON自我描述的,易于理解

因此,让我们开始编码。

步骤1:运行Dotnet命令

打开命令行窗口,转到您的存储库文件夹,并通过键入下一个dotnet命令来创建新的API项目:

dotnet new webapi - n crudstore

步骤2:探索您的项目

输入以下内容,进入项目crudstore

cd crudstore

通过输入以下代码在vscode中打开您的项目:

code .

步骤3:设定环境

单击扩展面板,然后探索大量工具,这些工具将帮助您准备环境并提高工作效率。

就个人而言,我建议您安装:

CC#扩展

步骤4:建立模型

namespace Models { public class Product { public int Idproduct { get; set; } public string Name { get; set; } public string Imageurl { get; set; } public decimal Price { get; set; } } }

步骤5:创建控制器

我将使用产品的静态集合来说明此示例,但是在实际情况下,当然,您将必须添加更多代码才能与数据库连接。

static List<product> _products = new List<product>(){ new Product(){ Idproduct =0, Name= "hard disk", Price= 100 }, new Product(){ Idproduct =1, Name= "monitor", Price= 250 }, };

之后,添加下一个代码来处理所有请求。

请注意,您必须在标头中使用一些名称空间:

 

using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Models;</code>

 

[Produces("application/json")] [ApiController] [Route("api/products")] public class productController : Controller { static List<Product> _products = new List<Product>(){ new Product(){ Idproduct =0, Name= "hard disk", Price= 100 }, new Product(){ Idproduct =1, Name= "monitor", Price= 250 }, }; [HttpGet("GetAll")] public IActionResult GetAll() { return Ok(_products); } [HttpPost] public IActionResult Post([FromBody] Product product) { _products.Add(product); return StatusCode(StatusCodes.Status201Created); } [HttpPut] public IActionResult Put([FromBody] Product product) { var entity = _products.Where (x => x.Idproduct == product.Idproduct).FirstOrDefault(); entity.Name = product.Name; entity.Price = product.Price; entity.Imageurl = product.Imageurl; return StatusCode(StatusCodes.Status200OK); } [HttpDelete] public IActionResult Delete([FromBody] Product product) { var entity = _products.Where (x => x.Idproduct == product.Idproduct).FirstOrDefault(); _products.Remove(entity); return StatusCode(StatusCodes.Status200OK); } }

6步:将Swagger添加到您的项目

Swagger块对于记录和描述API中的所有方法非常有用。在命令行和项目内部,键入下一个命令:

dotnet add package Swashbuckle.AspNetCore

结果,您将看到以下消息:

转到项目中的startup.cs类,并进行一些更改以允许适当地配置swagger

Configureservices方法中,添加以下代码:

services.AddCors(o => o.AddPolicy("MyPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen();

之后,转到Startup类中的Configure方法并添加以下代码:

// Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });

最后,您的Startup类应如下所示:

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. // Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddCors(o => o.AddPolicy("MyPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(); } // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }

步骤7:测试您的API

在命令行窗口中键入下一个命令:

dotnet run

步骤8:验证结果

打开浏览器并输入URL https://localhost:5001/swagger/index.html,您将看到我们之前创建的方法集。

方法GetAll

网址:https://localhost:5001/api/products/GetAll

[ { "idproduct": 0, "name": "hard disk", "imageurl": null, "price": 100 }, { "idproduct": 1, "name": "monitor", "imageurl": null, "price": 250 } ]

方法Post

网址:https://localhost:5001/api/products

{ "idproduct": 0, "name": "watch", "imageurl": "http://url", "price": 150 }

您可以探索Swagger提供的用于测试API的所有功能,因此您可以使用其他有趣的替代方法(例如PostmanFiddler来测试API

希望您喜欢此代码!

下载Github的代码
最新回复(0)