项目准备
1.创建项目,选择webapi。取消勾选使用控制器。创建minimal Api项目
2.创建成功后MinimalAPI的接口直接写在program.cs中
3.引入nuget包:Masa.Contrib.Service.MinimalAPIs
MinimalAPI改造
1. 在program.cs中加入以下内容
将原有的
var app = builder.Build();
换成
var app = builder.Services.AddServices(builder);
2.自定义Service并继承ServiceBase
1.我们创建的一个自定义service如下:
public class UserService : ServiceBase {
public UserService() : base() {
App.MapGet("/api/weatherforecast", GetWeatherForecast);
}
public async Task<WeatherForecast[]> PostWeather() {
return null;
}
public async Task< WeatherForecast[]> GetWeatherForecast() {
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
}
public async Task<IResult> Register() {
return Results.Ok("注册成功");
}
}
public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) {
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
2.构建成功,查看swagger
提问:为什么我们只写了一个app.MapGet,却生成了三个接口
MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口:https://note.raokun.top/archives/masaminimalapi-yuan-ma-jie-xi--wei-shen-me-wo-men-zhi-xie-le-yi-ge-appmapget-que-sheng-cheng-le-san-ge-jie-kou