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

发布时间 2023-05-05 17:41:02作者: rrrrrsddds

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

1.ServiceBase

1.AutoMapRoute

源码如下:

image-1683277238491

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方法代码:

image-1683277247813

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

3. ParseMethodPrefix

ParseMethodPrefix源码:

image-1683277257625

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

4.ServiceGlobalRouteOptions

ServiceGlobalRouteOptions源码:

image-1683277265824

ServiceGlobalRouteOptions配置方法前缀。

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

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

5.关闭自动创建接口 AutoMapRoute

在构造函数中加入

RouteOptions.DisableAutoMapRoute = true;

禁用AutoMapRoute

image-1683277276893

禁用后swagger:

image-1683277284836

可以看到,禁用后,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
  1. 添加MinimalAPI
var builder = WebApplication.CreateBuilder(args);
var app = builder.Services.AddServices(builder);
  1. 自定义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