MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口

2023-07-31,,

源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口

1.ServiceBase

1.AutoMapRoute

源码如下:

AutoMapRoute自动创建map路由,MinimalAPI会根据service中的方法,创建对应的api接口。

比如上文的一个方法:

public async Task<WeatherForecast[]> PostWeather() {
return null;
}

MinimalAPI会帮我们生成一个Post 的Weather接口,接口地址:

http://localhost:5187/api/v1/Users/Weather

2.ParseMethod

ParseMethod方法代码:

methodName 是方法名。PostWeather方法帮我们解析方法名中的关键信息生成对应请求类型。

3. ParseMethodPrefix

ParseMethodPrefix源码:

ParseMethodPrefix 用于判断自定义的方法前缀。

4.ServiceGlobalRouteOptions

ServiceGlobalRouteOptions源码:

ServiceGlobalRouteOptions配置方法前缀。

例如 方法前缀是Find,这个方法就会被解析成get请求。

注意:PostWeather 会生成 /api/v1/Users/Weather 。就是根据ServiceGlobalRouteOptions配置的。

5.关闭自动创建接口 AutoMapRoute

在构造函数中加入

RouteOptions.DisableAutoMapRoute = true;

禁用AutoMapRoute

禁用后swagger:

可以看到,禁用后,swagger就只有我们通过App.MapGet创建的接口了。

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);
}
阅读如遇样式问题,请前往个人博客浏览: https://note.raokun.top
拥抱ChatGPT,国内访问网站:https://ai.firstsaofan.top
开源项目地址:https://github.com/firstsaofan/TerraMours

MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口的相关教程结束。

《MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口.doc》

下载本文的Word格式文档,以方便收藏与打印。