1.Restful风格
Program.cs的代码
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); WebApplication app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); app.MapGet("GetRequest",()=>"This is a Get Request"); app.MapPost("PostRequest", () => "This is a Post Request"); app.MapPut("PutRequest", () => "This is a Put Request"); app.MapDelete("DeleteRequest", () => "This is a Delete Request"); app.MapMethods("AllRequest",new string[] { "GET","POST","PUT","DELETE","OPTIONS","HEAD"},()=> "This is a ALL Request"); app.Run();
2.分类来写API
如果api过多,全部写在program.cs中显得过于复杂,这时可以使用扩展类实现分类写API
(1)项目结构
(2)PhoneApiExtensions.cs
namespace Advanced.NET6.WebApi { public static class PhoneApiExtensions { public static void PhoneApi(this WebApplication app) { app.MapGet("/GetOPPO", () => { return new { Port = app.Configuration["Port"], Name = "OPPO手机", Remark = $"数据来自于:{app.Configuration["Port"]}的服务器" }; }).WithTags("Phone"); app.MapPost("/AddOPPO", () => { return new { Result = true, Message = "操作成功" }; }).WithTags("Phone"); app.MapPut("/AddOPPONew", () => { return new { Result = true, Message = "操作成功" }; }).WithTags("Phone"); app.MapDelete("/DelOPPO", () => { return new { Result = true, Message = "操作成功" }; }).WithTags("Phone"); } } }
(3)ProductApiExtensions.cs
namespace Advanced.NET6.WebApi { public static class ProductApiExtensions { public static void ProductApi(this WebApplication app) { app.MapGet("/GetIPhone13", () => { return new { Id = 123, Name = "IPhone13" }; }).WithTags("Product"); app.MapGet("/test/GetHuaWeiP40", () => { return new { Port = app.Configuration["Port"], Name = "华为P40", Remark = $"当前这条信息来自于:{app.Configuration["Port"]}的服务器", Date = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }; }).WithTags("Product"); } } }
(4)Program.cs
using Advanced.NET6.WebApi; var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); #region 自定义的api //如果api一旦过多,api过于复杂 //解决方案: //1.还是使用带有控制器的weapi //2.如果使用MinimalApi--分类来写API --扩展类的方式 app.ProductApi(); app.PhoneApi(); #endregion app.Run();
(5)Swagger显示