源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口
1.ServiceBase
1.AutoMapRoute
比如上文的一个方法:
public async Task<WeatherForecast[]> PostWeather( {
return null;
}
MinimalAPI会帮我们生成一个Post 的Weather接口,接口地址:
http://localhost:5187/api/v1/Users/Weather
2.ParseMethod
ParseMethod方法代码:
3. ParseMethodPrefix
ParseMethodPrefix源码:
4.ServiceGlobalRouteOptions
ServiceGlobalRouteOptions源码:
例如 方法前缀是Find,这个方法就会被解析成get请求。
注意:PostWeather 会生成 /api/v1/Users/Weather 。就是根据ServiceGlobalRouteOptions配置的。
5.关闭自动创建接口 AutoMapRoute
RouteOptions.DisableAutoMapRoute = true;
禁用AutoMapRoute
MASA minimalAPI 官方文档
原始用法:
var builder = WebApplication.CreateBuilder(args;
var app = builder.Build(;
app.MapGet("/api/v1/Demo/HelloWorld", ( => "Hello World";
app.Run(;
用例:
Install-Package Masa.Contrib.Service.MinimalAPIs
- 添加MinimalAPI
var builder = WebApplication.CreateBuilder(args;
var app = builder.Services.AddServices(builder;
- 自定义Service并继承ServiceBase,如:
public class DemoService : ServiceBase
{
public string HelloWorld(
{
return "Hello World";
}
}
提示:继承ServiceBase的服务为单例模式注册,如果需要从DI获取获取
public async Task DeleteBasketByIdAsync(string id, [FromServices] IBasketRepository repository
{
await repository.DeleteBasketAsync(id;
}