广辉 发表于 2023-5-5 21:51:50

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

源码解析:为什么我们只写了一个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/Weather2.ParseMethod

ParseMethod方法代码:
https://note.raokun.top/upload/2023/05/image-1683277247813.png
methodName 是方法名。PostWeather方法帮我们解析方法名中的关键信息生成对应请求类型。
3. ParseMethodPrefix

ParseMethodPrefix源码:

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

ServiceGlobalRouteOptions源码:
https://note.raokun.top/upload/2023/05/image-1683277265824.png
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, IBasketRepository repository)
{
    await repository.DeleteBasketAsync(id);
}阅读如遇样式问题,请前往个人博客浏览: https://note.raokun.top

拥抱ChatGPT,国内访问网站:https://ai.firstsaofan.top

开源项目地址:https://github.com/firstsaofan/TerraMours


来源:https://www.cnblogs.com/raok/archive/2023/05/05/17374885.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接