RestFul Api(Representational State Transfer)
是现在一种流行的 API 设计风格1,有利于前后端分离的系统开发,数据请求与交互通过 URL 的 Api 来实现。
这里留下
RestFul Api
的理论教程:https://www.runoob.com/w3cnote/restful-architecture.html
下面将简单展示以下在 .Net Core
中的一个简单 RestFul Api
开发。
创建项目
打开 Visual Studio 2019
,创建一个 ASP.NET Core 空
的项目。
控制器服务注入
直到这一步,项目已经创建成功,打开 Startup.cs
文件,有如下代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPIDemo
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(setupAction =>
{
setupAction.ReturnHttpNotAcceptable = true;
});
}
// 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();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
此时如果创建控制器并不会成功,需要将控制器的路由添加到项目中。如下代码所示:
// 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();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
// 添加这一句指令,那么系统就会通过路由访问到指定的控制器 API
endpoints.MapControllers();
});
}
创建一个 API
在项目中创建一个文件夹 Controllers
,即项目控制器存放位置,注意是复数形式命名。而后在 Controllers
中创建一个 API 控制器 ApiDemoController.cs
,示例代码如下所示。
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPIDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ApiDemoController : ControllerBase
{
// 一个 Get 请求的 Api ,请求URL:https://localhost:5001/api/ApiDemo
[HttpGet]
public IActionResult GetDataDemo()
{
// 返回 200 OK
return Ok("网络请求成功!");
}
}
}
运行程序
现在,一个简单的 Http 请求的 Api 已经做好了,可以在浏览器或者 Postman 中去发送 https://localhost:5001/api/ApiDemo
这个请求了。
参考资源
是一种设计风格,但并不是一种标准。 ↩︎