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显示
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义