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

科技资讯 投稿 5300 0 评论

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

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

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

赞同 (22) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽