.Net Core 6新功能Minimal Api简单使用
Minimal Api字面意思就是最小的api,用过.net core api的应该对core的web api机制不陌生。
首先新建一个web api空项目
创建空项目一定要取消勾选使用控制器,如果是创建.net core空项目则没有该选项。创建完成打开program
var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateTime.Now.AddDays(index), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast"); app.Run(); internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }
还是熟悉的天气预报,相较于之前wei api,minimalapi省去了控制器,更加精简。运行程序
minimal api只要Get、Post、Put、Delete四种请求方式。
新增一个post方法
app.MapPost("/addUser", (string id) => { return $"{id} "; });
运行程序
参数默认成为了query传参。接着修改一下addUser
app.MapPost("/addUser", (string id, UserModel user) => { return $"{id}:{user.Name} "; });
在原来的接口上新增一个实体接受参数,运行程序
实体参数默认成了body传参。这是因为c#10的新特性,实体自动识别,目前我还没有发现怎么指定参数的接收方式。总结就是实体会用body传参,int string这些会走query。如有不对欢迎指正纠错。