MASAMinimalAPI:创建MinimalAPI项目
项目准备1.创建项目,选择webapi。取消勾选使用控制器。创建minimal Api项目
2.创建成功后MinimalAPI的接口直接写在program.cs中
3.引入nuget包:Masa.Contrib.Service.MinimalAPIs
https://note.raokun.top/upload/2023/05/image-1683276817049.png
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
))
.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
https://www.cnblogs.com/./img/image-20230505162450695.png
提问:为什么我们只写了一个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
阅读如遇样式问题,请前往个人博客浏览: https://note.raokun.top
拥抱ChatGPT,国内访问网站:https://ai.firstsaofan.top
开源项目地址:https://github.com/firstsaofan/TerraMours
来源:https://www.cnblogs.com/raok/archive/2023/05/05/17374688.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]