# 动态 Restful API 生成

# 介绍

通常在DDD开发架构中,我们写完服务层需要在控制器中写API,今天介绍一个组件 Plus.AutoApi 可以用它来动态生成 Restful 风格的 WebApi,不用写 Controller。

# 快速使用

在你的应用服务层中添加组件

Install-Package Plus.AutoApi
1

在 Startup 中注册 AutoApi

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoApi(x => { });
}
1
2
3
4

AddAutoApi 同时也支持各种 Options 参数,可以自行查看。

让你的服务直接或者间接实现IAutoApi,添加特性[AutoApi]即可,示例代码如下:

[AutoApi]
public class WeatherService : IAutoApi
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    public IEnumerable<WeatherForecast> Get()
    {
        return WeatherForecast();
    }

    [HttpGet("{id}")]
    public IEnumerable<WeatherForecast> Get(int id)
    {
        return WeatherForecast();
    }

    public IEnumerable<WeatherForecast> Post()
    {
        return WeatherForecast();
    }

    [HttpPut("{id}")]
    public IEnumerable<WeatherForecast> Put(int id)
    {
        return WeatherForecast();
    }

    [HttpDelete("{id}")]
    public IEnumerable<WeatherForecast> Delete(int id)
    {
        return WeatherForecast();
    }

    private static IEnumerable<WeatherForecast> WeatherForecast()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        }).ToArray();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

需要注意的是你的服务层命名规范,默认要以Service或者ApplicationService结尾,也可以通过配置替换默认名称。

如果你想让某个服务不自动生成API,可以给特性传递参数:[AutoApi(Disabled = true)]

让生成的API兼容 Swagger,需要添加下面这句代码。








 


services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Plus AutoApi Sample",
        Version = "v1.0.0"
    });
    options.DocInclusionPredicate((docName, description) => true);
});
1
2
3
4
5
6
7
8
9

同时自动生成API也可以和控制器共存,互不影响。你可以手动指定HTTP方法,也可以根据默认规则自动创建。

默认自动创建HTTP方法的规则如下:

static PlusConsts()
{
    HttpVerbs = new Dictionary<string, string>()
    {
        ["add"] = "POST",
        ["create"] = "POST",
        ["post"] = "POST",
        ["insert"] = "POST",
        ["get"] = "GET",
        ["find"] = "GET",
        ["fetch"] = "GET",
        ["query"] = "GET",
        ["update"] = "PUT",
        ["put"] = "PUT",
        ["delete"] = "DELETE",
        ["remove"] = "DELETE"
    };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

上面代码最终生成的API路由如下:

# Samples

https://github.com/Meowv/Plus.AutoApi/tree/master/samples/Plus.AutoApi.Sample (opens new window)

# Nuget

https://www.nuget.org/packages/Plus.AutoApi (opens new window)

# 开源地址

https://github.com/Meowv/Plus.AutoApi (opens new window)