項目準備 1.創建項目,選擇webapi。取消勾選使用控制器。創建minimal Api項目 2.創建成功後MinimalAPI的介面直接寫在program.cs中 3.引入nuget包:Masa.Contrib.Service.MinimalAPIs MinimalAPI改造 1. 在progra ...
項目準備
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